Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a list and an iterator to form a new list

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.

like image 813
Adam Avatar asked Jan 03 '23 11:01

Adam


2 Answers

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.

like image 144
Willem Van Onsem Avatar answered Jan 06 '23 02:01

Willem Van Onsem


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]
like image 24
Moses Koledoye Avatar answered Jan 06 '23 02:01

Moses Koledoye