I tried:
a_list = [1,2,3]
b_list = [4,5]
...
call_function(a_list + iter(b_list)) # TypeError
Is there a better code than this:
a_list = [1,2,3]
b_list = [4,5]
...
new_list = a_list[:]
new_list += iter(b_list) # no TypeError?
call_function(new_list)
Consider any iterator, I'm using islice
in place of iter
.
In python-3.5, you can use iterable unpacking:
call_function([*a_list, *iter(b_list)])
This works since:
>>> [*a_list, *iter(b_list)]
[1, 2, 3, 4, 5]
Notice the asterisk (*
) in front of both a_list
and iter(b_list)
. Furthermore a_list
only has to be a finite iterable/iterator. So you can simply construct a list that concatenates finite iterables together.
You can generally use itertools.chain
to join iterables:
from itertools import chain
new_list = list(chain(a_list, iter(b_list)))
print(new_list)
# [1, 2, 3, 4, 5]
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