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 = i + 0
Can some one help me to build this?
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 will be the first and the second element respectively.
new_data = [[i+1, j, j] 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)]
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']]