Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add all elements of an iterable to list

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) 
like image 871
Bartlomiej Lewandowski Avatar asked Dec 15 '13 08:12

Bartlomiej Lewandowski


People also ask

How do you sum elements in a list?

Sum Of Elements In A List Using The sum() Function. Python also provides us with an inbuilt sum() function to calculate the sum of the elements in any collection object. The sum() function accepts an iterable object such as list, tuple, or set and returns the sum of the elements in the object.

How do you add all the numbers in a list in Python?

Python provides an inbuilt function called sum() which sums up the numbers in a list.

How do you add a set to a list in Python?

To add a list to set in Python, use the set. update() function. The set. update() is a built-in Python function that accepts a single element or multiple iterable sequences as arguments and adds that to the set.


1 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.

like image 131
Martijn Pieters Avatar answered Sep 26 '22 00:09

Martijn Pieters