Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

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
like image 677
Timur Avatar asked Aug 20 '12 15:08

Timur


People also ask

How do you pop an entire list in Python?

The methods are remove(), pop() and clear(). It helps to remove the very first given element matching from the list. The pop() method removes an element from the list based on the index given. The clear() method will remove all the elements present in the list.

What does pop () do in Python?

The pop() method removes the element at the specified position.

What is the time complexity of pop ()?

pop() is O(1).

What is the list pop () method?

Python List pop() Method. Python list pop() is an inbuilt function in Python that removes and returns the last value from the List or the given index value.

Can you pop value in list Python?

The method pop() can be used to remove and return the last value from the list or the given index value. If the index is not given, then the last element is popped out and removed.


2 Answers

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)
like image 167
g.d.d.c Avatar answered Nov 07 '22 14:11

g.d.d.c


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

like image 33
Jens Timmerman Avatar answered Nov 07 '22 14:11

Jens Timmerman