Iterate over two lists one after another

I have two lists list1 and list2 numbers, and I want to list1 over them with the same instructions. Like this:

 for item in list1: print(item.amount) print(item.total_amount) for item in list2: print(item.amount) print(item.total_amount) 

But that seems redundant. I know that I can write for item in list1 + list2: but it has a runtime price.

Is there any way to do this without free time?

+9
source share
3 answers

This can be done using itertools.chain :

 import itertools l1 = [1, 2, 3, 4] l2 = [5, 6, 7, 8] for i in itertools.chain(l1, l2): print(i, end=" ") 

Which will print:

 1 2 3 4 5 6 7 8 

According to the documentation, chain performs the following actions:

Create an iterator that returns items from the first iteration until it is exhausted, then proceeds to the next iteration until all iterations are exhausted.

If you have lists in the list, itertools.chain.from_iterable is available:

 l = [l1, l2] for i in itertools.chain.from_iterable(l): print(i, end=" ") 

Which gives the same result.

If you do not want to import a module for this, writing a function for it is quite simple:

 def custom_chain(*it): for iterab in it: yield from iterab 

This requires Python 3, for Python 2, only yield them back using a loop:

 def custom_chain(*it): for iterab in it: for val in iterab: yield val 

In addition to the previous, Python 3.5 with extended generalizations for unpacking also allows you to unpack a literal in a list:

 for i in [*l1, *l2]: print(i, end=" ") 

although this is slightly faster than l1 + l2 it still creates a list, which is then discarded; just go for it as a final decision.

+23
source

chain works, but if you feel like it is overloading to import a module to only call one function once, you can replicate its inline behavior:

 for seq in (list1, list2): for item in seq: print(item.amount) print(item.total_amount) 

Creating a tuple (list1, list2) is O (1) relative to the length of the list, so it should act favorably compared to combining lists together.

+2
source

How about this:

 for item in list1 + list2: print(item.amount) print(item.total_amount) 

Only 3 lines

0
source

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


All Articles