user1073865
user1073865

Reputation: 2593

positions in a list. python

Lets say I have this list:

   lst =  [[0], [0, 0], [0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0, 0]...]

how can I add a certain number to each cell according to its position in the lists for exapmle: I want to add a formula to each cell by multipying 3 with the position on the list*position in the nested list so lets say the second cell on the third list will be

                            3*3*2
(random number)*(the third nested list)*(second spot on that list)

so eventually the list will look like that (only for the number 3)

   lst =  [[3], [6, 12], [9, 18, 27], [12, 24, 36, 48], [15, 30, 45, 60, 75]...]

anyway this is just an example and Im asking generally about how to apply a certain formula considaring the position of nested list and inner cells in a list. Its kind of difficult to explain so I hope it came out clear enough. thank you.

Upvotes: 1

Views: 125

Answers (1)

Free Monica Cellio
Free Monica Cellio

Reputation: 2290

Looks like a job for enumerate!

for i, sublist in enumerate(lst):
    for j, elem in enumerate(sublist):
        sublist[j] = 3*(i+1)*(j+1)

Upvotes: 5

Related Questions