How to replace the first element of every list in a list of lists?

Question:

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"]]
Asked By: Aran Joyce

||

Answers:

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')
Answered By: Gary02127

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.

Answered By: Adam Luchjenbroers

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']]
Answered By: Mark

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']]
Answered By: Stoner
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.