Timur
Timur

Reputation: 162

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

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

Upvotes: 8

Views: 14523

Answers (4)

user7387072
user7387072

Reputation:

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']

Upvotes: 1

Maksim Kneller
Maksim Kneller

Reputation: 297

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)]

Upvotes: 3

Jens Timmerman
Jens Timmerman

Reputation: 9816

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...

Upvotes: 3

g.d.d.c
g.d.d.c

Reputation: 47978

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)

Upvotes: 11

Related Questions