Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python for each but stop after n elements

Tags:

python

I have a list of dicts that can be anywhere from 0 to 100 elements long. I want to look through the first three elements only, and I don't want to throw an error if there are less than three elements in the list. How do I do this cleanly in python?

psuedocode:

for element in my_list (max of 3):
    do_stuff(element)

EDIT: This code works but feels very unclean. I feel like python has a better way to do this:

counter = 0
while counter < 3:
    if counter >= len(my_list):
        break

    do_stuff(my_list[counter])
    counter += 1
like image 812
MattF Avatar asked Dec 15 '22 21:12

MattF


2 Answers

You could use itertools.islice:

for element in itertools.islice(my_list, 0, 3):
    do_stuff(element)

Of course, if it actually is a list, then you could just use a regular slice:

for element in my_list[:3]:
    do_stuff(element)

Regular slices on normal sequences are "forgiving" in that if you ask for more elements than are there, no exception will be raised.

like image 146
mgilson Avatar answered Dec 17 '22 11:12

mgilson


Slice the list:

for element in my_list[:3]:
    do_stuff(element)

Documentation says that there won't be any errors if the list doesn't have elements on those indices, thus you can safely use that on lists containing less than 3 elements. List slicing returns a new list.

The slightly more efficient way (for big slices) would be to use itertools.islice:

for element in islice(my_list, 0, 3): # or islice(my_list, 3)
    do_stuff(element)
like image 38
vaultah Avatar answered Dec 17 '22 09:12

vaultah