1

As explained in the answer to this question for loops in python do not work by reference. Therefore, a program like that

a=[1,2,3]
for el in a:
    el += 1
print(a)

will not modify a.

In c++ there is instead the possibility to have for loops either by copy or reference. For instance, the following c++ code modifies the contents of the array a

std::array<int, 3> a{1, 2, 3};
for auto& el : a
    el += 1;

Is there a way to implement a syntax in python that achieve the same as the c++ loop above?

Edit: to be more precise, I am looking forward to a syntax such that, analogous to the c++ example, I have inside the loop a sort-of-reference to the elements of a.

francesco
  • 7,189
  • 7
  • 22
  • 49
  • 1
    Something like: `for i,v in enumerate(a): a[i] += 1` ? – Ank May 31 '21 at 15:49
  • @Ank well, that would certainly work. But ```v``` has, again, a value semantic and I cannot use it to update a. – francesco May 31 '21 at 15:56
  • 1
    AFAIK you cannot do it with `v` then in python. You will have to do via indexes or the elements inside list themselves have to be mutable to do it via `v`. Both languages are different in this regard. You can check this [post](https://softwareengineering.stackexchange.com/questions/341179/why-does-python-only-make-a-copy-of-the-individual-element-when-iterating-a-list) as well for more info. – Ank May 31 '21 at 16:27

4 Answers4

1
a=[1,2,3]
for i, el in enumerate(a):
    a[i] += 1
print(a)
jeed
  • 136
  • 5
0

How about you do this:

a = [1, 2, 3]
for i in range(len(a)):
   temp = a[i]
   a.pop(i)
   a.insert(i, temp+1)

You're simply replacing the elements with newer values.

Rahil Kadakia
  • 135
  • 1
  • 6
0

This is because "el" is a copy of each element in the list

You can do this to edit the list

a=[1,2,3]
for el in range(len(a)):
    a[el] += 1
print(a)
Alan
  • 24
  • 2
  • 2
0

The problem is the elements of the list are integers which are immutable (unchangable). A workaround would be to replace them with something that was, like a (nested) list:

a = [[1], [2], [3]]
for el in a:
    el[0] += 1
print(a)  # -> [[2], [3], [4]]

However since a itself is mutable, you could simply to this:

a = [1, 2, 3]
for i in range(len(a)):
    a[i] += 1
print(a)  # -> [2, 3, 4]
martineau
  • 119,623
  • 25
  • 170
  • 301