Adam
Adam

Reputation: 1817

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.

Upvotes: 4

Views: 113

Answers (4)

Kruupös
Kruupös

Reputation: 5474

You can use __iadd__() which is the real function trigger by the syntactic sugar += (That's why it doesn't create an error).

call_function(a_list.__iadd__(iter(b_list)))

Produce

>>> a_list.__iadd__(iter(b_list))
[1, 2, 3, 4, 5]

This is fun but not really good in term of readability to be honest. Prefer other answers :)

EDIT:

Of course to produce new_list, you have to make a copy of list_a has you did in your question.

a_list[:].__iadd__(iter(b_list))

Upvotes: 1

cs95
cs95

Reputation: 402613

The existing answers already address the workaround. Additionally, this line:

new_list += iter(b_list)

Does not throw an error, because it calls list.__iadd__ which supports the addition of iterators.

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476750

In , 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.

Upvotes: 4

Moses Koledoye
Moses Koledoye

Reputation: 78554

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]

Upvotes: 3

Related Questions