Hcc
Hcc

Reputation: 11

How to modify a list in place

I want to add 1 to each element in the list without creating new one

i = [1,2,3,4,5]
for each in i:
    i[i.index(each)] = each+1
print(i)

but it return like this...

[6,2,3,4,5]

seems that one add one in first element..but I want to add one for each..

Upvotes: 0

Views: 2858

Answers (3)

Smart Manoj
Smart Manoj

Reputation: 5824

After incrementing 1 the next time i.index(each) always returns the first element in this case

for idx in range(len(i)):i[idx]+=1

Upvotes: -1

Druta Ruslan
Druta Ruslan

Reputation: 7402

lst = [1,2,3,4,5]
for i, x in enumerate(lst):
    lst[i] = x + 1
print(lst)

Output

[2, 3, 4, 5, 6]

Upvotes: 6

Rakesh
Rakesh

Reputation: 82765

Try using range of len of list

Ex:

i = [1,2,3,4,5]
for each in range(len(i)):
    i[each]= i[each]+1
print(i)

Output:

[2, 3, 4, 5, 6]

Upvotes: 0

Related Questions