Dany Dany - 1 month ago 11
Python Question

Confusion about Python list result

Here's the code:

a=[1,2,3]
a[1]=10,20,30
print a
a[1:2]=10,20,30
print a
a[1:2]=[10,20,30]
print a


The result is:

[1, (10, 20, 30), 3]
[1, 10, 20, 30, 20, 30]
[1, 10, 20, 30, 20, 30, 3]


Can anyone tell me what happened?

Answer
a=[1,2,3]
print a
a[1]=10,20,30  # add a tuple at position 1
print a  
a[1:2]=10,20,30 #replaces tuple and inserts 10,20,30 at position 1
print a  
a[1:2]=[10,20,30] #now a[1:2] is 10 so this replaces 10 and inserts 10,20,30 at position 1 
print a 

OUTPUT

[1, 2, 3]
[1, (10, 20, 30), 3]
[1, 10, 20, 30, 3]
[1, 10, 20, 30, 20, 30, 3]

Note: There is never a 30 at the end. Hope this helps.

Comments