0

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..

roganjosh
  • 12,594
  • 4
  • 29
  • 46
Hcc
  • 11
  • 1
  • 2
    @zimdero no you don't at all. Lists are mutable. – roganjosh Jun 16 '18 at 08:41
  • 2
    @Abhishek That dupe does not answer the question. The OP does not want to create a new list object, they want to modify an existing one – roganjosh Jun 16 '18 at 08:42
  • The dupe target answers the question but (bizarrely) creates a new list. – jedwards Jun 16 '18 at 08:45
  • @jedwards I disagree. Just because the outcome is numerically the same doesn't mean it answers the question because the OP is explicit in "...in the list without creating new one" – roganjosh Jun 16 '18 at 08:47
  • @roganjosh sorry I wasn't clear with my "answers the question". I'm in agreement that it's not a great dupe target. – jedwards Jun 16 '18 at 08:48
  • @khelwood I've just retracted my dupe target too since it's incidental that they do the modification in place. "python modify list in place" gave that as the first answer though. What is the canonical here? – roganjosh Jun 16 '18 at 08:51
  • There is often no *benefit* to operating in place. A list comprehension is O(n), as is an in-place method. If you really care about performance / memory, consider using a specialist library such as NumPy. – jpp Jun 16 '18 at 10:05

3 Answers3

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

Output

[2, 3, 4, 5, 6]
Druta Ruslan
  • 7,171
  • 2
  • 28
  • 38
0

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]
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • Down-voter can you please tell if this is the wrong approach? – Rakesh Jun 16 '18 at 08:44
  • I'm not the downvoter, but you can bet you've been downvoted for using a C-style loop ( `for index in range(len(seq))`) instead of the much more idiomatic `for index, item in enumerate(seq)`. My 2 cents... – bruno desthuilliers Jun 16 '18 at 09:22
  • oh ok...I did not use `enumerate` because i thought that was....unnecessary for this task. Guess i was wrong. Thanks anyway :). I learn a lot coding in stackoverflow :). – Rakesh Jun 16 '18 at 09:40
-1

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
Smart Manoj
  • 5,230
  • 4
  • 34
  • 59