Reputation: 101
I have a list like this:
a = [(1,2,3,4), (2,3,2,2), (33,221,22,1) ...]
and I want to add for each item in the list a 5th value, for example:
new_a = [(1,2,3,4,"new"), (2,3,2,2,"new"), (33,221,22,1,"new") ...]
How can I do that because a.list or a.add freeze my computer.
for item in a:
a.add("new") or a.append("new")
Upvotes: 1
Views: 81
Reputation: 21446
You can use map
>>> map(lambda x: x + ('new',), a)
[(1, 2, 3, 4, 'new'), (2, 3, 2, 2, 'new'), (33, 221, 22, 1, 'new')]
Upvotes: 0
Reputation: 40516
The inner items are not lists, they are tuples. Tuples are immutable. Therefore, you probably need to create new tuples that contain the values you want:
new_a = [x + ('new',) for x in a]
This code iterates through all tuples present in a and for each one creates a new tuple consisting of the values of the original, plus the value 'new'
(the value ('new',)
is a tuple literal: it creates a new tuple with one value).
In the end, all the values created are assigned to the new list.
Upvotes: 2