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
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With