Reputation: 7576
I want to do the following elegantly. I have a list:
list1 = [[1,2],[3,1,4,7],[5],[7,8]]
I'd like to append the number 1 to each element of the list, so that I have
list1 = [[1,2,1],[3,1,4,7,1],[5,1],[7,8,1]]
I'm trying to map this via
map(list.append([1]), vectors)
but this returns the error append() takes exactly one argument (0 given)
and if I just try append([1])
(without list.
), I get NameError: global name 'append' is not defined
. I guess I could do it with a loop, but this seems more elegant, is there a way to map this correctly?
Upvotes: 3
Views: 6319
Reputation: 1954
Here is a several ways to implement what you want:
More readable and classic way
for el in list1:
el.append(1)
List comprehension
list1 = [el + [1] for el in list1]
Generators:
list1 = (el + [1] for el in list1)
Map
list1 = map(lambda el: el + [1], list1)
What to use?
It depends on you own situation and may depends on execution speed optimizations, code readability, place of usage.
Map
is a worst choice in case of readability and execution speedFor
is a fastest and more plain way to do thisGenerators
allows you to generate new list only when you really need thisList comprehension
- one liner for classic for
and it takes advantage when you need quickly filter the new list using if
i.e. if you need only add element to each item - for
loop is a best choice to do this, but if you need add item
only if item
> 40, then you may consider to use List comprehension
.
For example:
Classic For
x = 41
for el in list1:
if x > 40:
el.append(x)
List comprehension
x = 1
list1 = [el + [x] for el in list1 if x > 40]
as @jmd_dk mentioned, in this sample is one fundamental difference: with simple for
you can just append to an existing object of the list which makes much less impact to execution time and memory usage. When you use List comprehension
, you will get new list object and in this case new list object for each item.
Upvotes: 4
Reputation: 19806
With list comprehension and append
, you can do:
list1 = [[1, 2], [3, 1, 4, 7], [5], [7, 8]]
[item.append(1) for item in list1]
print(list1) # Output: [[1, 2, 1], [3, 1, 4, 7, 1], [5, 1], [7, 8, 1]]
Output:
>>> list1 = [[1, 2], [3, 1, 4, 7], [5], [7, 8]]
>>> [item.append(1) for item in list1]
[None, None, None, None]
>>> list1
[[1, 2, 1], [3, 1, 4, 7, 1], [5, 1], [7, 8, 1]]
You may also use extend
like this:
[item.extend([1]) for item in list1]
print(list1) # Output: [[1, 2, 1], [3, 1, 4, 7, 1], [5, 1], [7, 8, 1]]
Upvotes: 0
Reputation: 4719
map(lambda x: x + [1], list1)
you mean this?
list.append() have NO return (mean always return None)
Upvotes: 0
Reputation: 13090
You can simply do
list1 = [[1,2],[3,1,4,7],[5],[7,8]]
for el in list1:
el.append(1)
Upvotes: 0
Reputation: 5888
Try a list comprehension, taking advantage of the fact the adding lists concats them together.
new_list = [l + [1] for l in list1]
Upvotes: 0