Home > Blockchain >  Iterating over lists produces unexpected results
Iterating over lists produces unexpected results

Time:04-12

In the first example below, I am iterating over a list of dataframes. The For loop creates column 'c'. Printing each df shows that both elements in the list were updated.

In the second example, I am iterating over a list of variables. The For loop applys some math to each element. But when printing, the list does not reflect the changes made in the For loop.

Please help me to understand why the elements in the second example are not being impacted by the For loop, like they are in the first example.

import pandas as pd

df1 = pd.DataFrame([[1,2],[3,4]], columns=['a', 'b'])
df2 = pd.DataFrame([[3,4],[5,6]], columns=['a', 'b'])

dfs = [df1, df2]
for df in dfs:
    df['c'] = df['a']   df['b']

print(df1)
print(df2)

result:

   a  b  c
0  1  2  3
1  3  4  7
   a  b   c
0  3  4   7
1  5  6  11

Second example:

a, b = 2, 3
test = [a, b]
for x in test:
    x = x * 2 
print(test)

result: [2, 3]

expected result: [4, 6]

CodePudding user response:

When you iterate in a list like this x takes the value at the current position.

for x in test:
    x = x * 2 

When you try to assign a new value to x you are not changing the element in the list, you are changing what the variable x contains.

To change the actual value in the list iterate by index:

for i in range(len(test)):
    test[i] = test[i] * 2

CodePudding user response:

In your second example, test is a list of ints which are not mutable. If you want a similar effect to your first snippet, you will have to store something mutable in your list:

a, b = 2, 3
test = [[a], [b]]
for x in test:
    x[0] = x[0] * 2 
print(test)

Output: [[4], [6]]

  • Related