Python for each, but stops after n elements

I have a list of dicts that can contain from 0 to 100 elements. I want to view only the first three elements, and I do not want to throw an error if the list has less than three elements. How to do this in python?

psuedocode:

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

EDIT: This code works, but feels very unclean. I feel that 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
+4
source share
4 answers

Draw a list:

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

The documentation says that there will be no errors if the list does not contain elements at these indices, so you can safely use this on lists containing less than 3 elements. Cutting a list returns a new list.

( ) itertools.islice:

for element in islice(my_list, 0, 3): # or islice(my_list, 3)
    do_stuff(element)
+4

itertools.islice:

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

, , :

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

"" , , , .

+5
for element in my_list[:3]:
    do_stuff(element)
+3
source

@mhawke is great if in fact it is listor something else that supports the slice interface.

For a more general iterative type, try convenient enumerate:

for ii, element in enumerate(my_list):
    if ii>=3:
        break
    do_stuff(element)
0
source

Source: https://habr.com/ru/post/1544842/


All Articles