Change the first index of each sublist in a list

3357 views python

Change the first index of each sublist in a list. from 1,2 , 3 ... for example -

data = [['45', 'gh', 'tg'], ['23', 'gf', 'gzs'], ['21', 'xzs', 'gd']]

I want to get

data = [[1, 'gh', 'tg'], [2, 'gf', 'gzs'], [3, 'xzs', 'gd']]

which means changing the first index of each sublist. I tried

for subs in data:
i = 0
subs[0] = i + 0

Can some one help me to build this?

answered question

I'm not exactly sure what you're trying to do in your attempt. subs[0] = i + 0 just after declaring i = 0?

something + 0 = the same something.

3 Answers


You can use a list comprehension using enumerate to get the index. i+1 is done to start the index from 1 because the default index starts from 0 in python enumerate.

enumerate returns the index and the individual elements of the enumerated list. j here will be the list and j[1] and j[2] will be the first and the second element respectively.

new_data = [[i+1, j[1], j[2]] for i, j in enumerate(data)]
# [[1, 'gh', 'tg'], [2, 'gf', 'gzs'], [3, 'xzs', 'gd']]

Another similar alternative is following where j[1:] refers to the rest of the list from second element until the last excluding the first. You then add the first index to create the final list.

new_data = [[i+1] + j[1:] for i, j in enumerate(data)]

posted this

Bazingaa's answer is probably the ideal solution, but here's another SUPER inefficient way using map. (I just think it's important to know about other solutions when solving a problem.)

list(map(lambda sublist: [data.index(sublist) + 1] + sublist[1:], data))
# => [[1, 'gh', 'tg'], [2, 'gf', 'gzs'], [3, 'xzs', 'gd']]

posted this

use enumerate to iterate the list You can pass an argument to enumerate to start the numbering from in your case it should start from 1

[[idx,lis[1],lis[2]] for idx,lis in enumerate(data,1)]

posted this

Have an answer?


Please login first before posting an answer.