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)
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.
Python provides an inbuilt function called sum() which sums up the numbers in a list.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With