I have two lists list1
and list2
of numbers, and I want to iterate 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 feels redundant. I know I can write for item in list1 + list2:
, but it has a price of running-time.
Is there a way do that without loose time?
chain
works, but if you feel that it's overkill to import a module just to call a single function once, you can replicate its behavior inline:Creating the (list1, list2) tuple is O(1) with respect to list length, so it should perform favorably in comparison to concatenating the lists together.
How about this:
Only 3 lines
This can be done with
itertools.chain
:Which will print:
As per the documentation,
chain
does the following:If you have your lists in a list,
itertools.chain.from_iterable
is available:Which yields the same result.
If you don't want to import a module for this, writing a function for it is pretty straight-forward:
This requires Python 3, for Python 2, just
yield
them back using a loop:In addition to the previous, Python
3.5
with its extended unpacking generalizations, also allows unpacking in the list literal:though this is slightly faster than
l1 + l2
it still constructs a list which is then tossed; only go for it as a final solution.