0

python 3.3.5. faced strange issue while working with List. In line 6th and 8th I am printing same variable but not sure why it is getting converted into uppercase

siblingList = [['Abc', 'Xyz', 'Def'],['Ghi','Jkl','Mno','Pqr'],['Stu', 'Pvw']]
siblingList1 = siblingList

for i in range(len(siblingList)):
    for j in range(len(siblingList[i])):
        print(siblingList[i][j])
        siblingList1[i][j] = siblingList[i][j].upper()
        print(siblingList[i][j])

Output:

Abc
ABC
Xyz
XYZ
Def
DEF
Ghi
GHI
Jkl
JKL
Mno
MNO
Pqr
PQR
Stu
STU
Pvw
PVW
Kumar Saurabh
  • 2,297
  • 5
  • 29
  • 43
  • 1
    What you think about this line `siblingList1[i][j] = siblingList[i][j].upper()`? – Mazdak Nov 27 '15 at 19:07
  • See [this question](http://stackoverflow.com/questions/9257094/how-to-change-a-string-into-uppercase) – jaredk Nov 27 '15 at 19:13

1 Answers1

0

Since you assign

siblingList1 = siblingList

that means that siblingList1 is the same thing as siblingList. When you do

siblingList1[i][j] = siblingList[i][j].upper()

in fact you are also modifying siblingList[i][j] to uppercase.

Adam Michalik
  • 9,678
  • 13
  • 71
  • 102
  • Thanks Adam. but in below case also behavior could have been same but same is not the case here. `var1 = 'abc' var2 = var1 var2 = var1.upper() print(var1) print (var2)` – Swapnil Shrivastava Nov 28 '15 at 06:25
  • `upper()` returns a new string. So `var1` is `'abc'` and `var2` first becomes `'abc'` but then becomes `'ABC'` - unrelated to `var1`. In your case you are modifying the **contents** of the arrays, not the array variables themselves. Maybe this will clarify: http://stackoverflow.com/q/11585886/466738 – Adam Michalik Nov 28 '15 at 08:44