Add all elements of an iterable to list

PythonListTuples

Python Problem Overview


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)

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBartlomiej LewandowskiView Question on Stackoverflow
Solution 1 - PythonMartijn PietersView Answer on Stackoverflow
Solution 2 - PythonthefourtheyeView Answer on Stackoverflow