How to pop() a list n times in Python?
I'll go ahead and post a couple answers. The easiest way to get some of a list is using slice
notation:
pl = pl[:5] # get the first five elements.
If you really want to pop from the list this works:
while len(pl) > 5:
pl.pop()
If you're after a random selection of the choices from that list, this is probably most effective:
import random
random.sample(range(10), 3)
Since this is a list, you can just get the last five elements by slicing it:
last_photos = photos[5:]
This will return a shallow copy, so any edit in any of the lists will be reflected in the other. If you don't want this behaviour you should first make a deep copy.
import copy
last_photos = copy.deepcopy(photos)[5:]
edit:
should of course have been [5:] instead of [:-5] But if you actually want to 'pop' it 5 times, this means you want the list without its last 5 elements...
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)]