Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make the same iteration for several different lists at the same time in Python

if i have multiple lists at different lengths is there a simple way to make the same iteration on all of them.

so insted of writing something like:

for item in list1:
    function(item)
for item in list2:
    function(item)
.
.
.
for item in listn:
   function(item)

i just write something like:

for item in list1,list2,...,listn:
    function(item)

I know you can do this by combining the lists by i want something more efficient than having to combine them each time i call the function

like image 539
foodisgood Avatar asked Apr 08 '26 02:04

foodisgood


1 Answers

Tasks which have to do with iteration are covered by the itertools module.

There you have a chain() function which can do

import itertools
for item in itertools.chain(list1, list2, list3):
    function(item)

BTW, the whole standard lib documentation is worth reading, there are a lot of interesting things which can prevent you from re-inventing the wheel.

like image 60
glglgl Avatar answered Apr 09 '26 14:04

glglgl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!