How to pop() a list n times in Python?

Viewed 10985

I have a photo chooser function that counts the number of files in a given directory and makes a list of them. I want it to return only 5 image URLs. Here's the function:

from os import listdir
from os.path import join, isfile

def choose_photos(account):
    photos = []
    # photos dir
    pd = join('C:\omg\photos', account)
    # of photos
    nop = len([name for name in listdir(location) if isfile(name)]) - 1
    # list of photos
    pl = list(range(0, nop))
    if len(pl) > 5:
        extra = len(pl) - 5
        # How can I pop extra times, so I end up with a list of 5 numbers
    shuffle(pl)
    for p in pl:
        photos.append(join('C:\omg\photos', account, str(p) + '.jpg'))
    return photos
4 Answers

In most languages pop() removes and returns the last element from a collection. So to remove and return n elements at the same time, how about:

def getPhotos(num):
    return [pl.pop() for _ in range(0,num)]

Quick and simple -

a = list("test string")
print(a[5:])#['s', 't', 'r', 'i', 'n', 'g']
a[:5] = []
print(a)#['s', 't', 'r', 'i', 'n', 'g']
Related