Reputation: 23
How to replace the first value in a list of lists with a new value?
list_of_lists = [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]]
new_values = [1, 2, 3]
for i in list_of_lists:
for n in range(len(new_values)):
list_of_lists[n][0] = new_values[n]
Desired output
list_of_lists = [[1, "b" ,"c"], [2, "e", "f"], [3, "h", "i"]]
Upvotes: 1
Views: 3438
Reputation: 5029
This one is actually quite simple
list_of_lists = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
new_values = [1, 2, 3]
for sub_list in list_of_lists:
sub_list[0] = new_values.pop(0)
This iterates over the lists and removes the first value of new_values each time.
Upvotes: 2
Reputation: 5699
Try:
list_of_lists = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
new_values = [1, 2, 3]
for n in range(len(list_of_lists)):
list_of_lists[n][0] = new_values[n]
Also, as a quicker way to set up the list_of_lists, one could say:
list_of_lists = [list('abc'), list('def'), list('ghi')]
Further, to avoid modifying the OP's original code as much as possible, one could insert the following line at the top, to define each letter variable to have its own character:
a, b, c, d, e, f, g, h, i = list('abcdefghi')
Upvotes: 2
Reputation: 916
Using enumerate to generate the index and list comprehension works too:
new_l = [[new_values[i]] + l[1:] for i, l in enumerate(list_of_lists)]
>>> new_l
[[1, 'b', 'c'], [2, 'e', 'f'], [3, 'h', 'i']]
Upvotes: 0
Reputation: 92461
Your code produces the correct output, but you don't need the outside loop:
for i in list_of_lists:
Notice you never use i
.
But really, there's a better way. Python makes it simple to avoid awkward structures like range(len(new_values))
. In this case you can simply zip your lists together and loop over that construct. This avoids the need to keep track of indexes — you just get the value and the list you want to alter in each loop iteration:
list_of_lists = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
new_values = [1, 2, 3]
for newVal, subList in zip(new_values, list_of_lists):
subList[0] = newVal
list_of_lists
will now look like:
[[1, 'b', 'c'], [2, 'e', 'f'], [3, 'h', 'i']]
Upvotes: 2