Add all elements of an iterable to list

Question:

Is there a more concise way of doing the following?

t = (1,2,3)
t2 = (4,5)

l.addAll(t)
l.addAll(t2)
print l # [1,2,3,4,5]

This is what I have tried so far: I would prefer to avoid passing in the list in the parameters.

def t_add(t,stuff):
    for x in t:
        stuff.append(x)

Answers:

Use list.extend(), not list.append() to add all items from an iterable to a list:

l.extend(t)
l.extend(t2)

or

l.extend(t + t2)

or even:

l += t + t2

where list.__iadd__ (in-place add) is implemented as list.extend() under the hood.

Demo:

>>> l = []
>>> t = (1,2,3)
>>> t2 = (4,5)
>>> l += t + t2
>>> l
[1, 2, 3, 4, 5]

If, however, you just wanted to create a list of t + t2, then list(t + t2) would be the shortest path to get there.

Answered By: Martijn Pieters

stuff.extend is what you want.

t = [1,2,3]
t2 = [4,5]
t.extend(t2)
# [1, 2, 3, 4, 5]

Or you can do

t += t2
Answered By: thefourtheye
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.