'Two ways of slicing Python nested lists

I have following code

mylst is a nested list:

mylst = [[507, 3, 30, 44, 522, 25],
[268, 40, 23, 54, 280, 67],
[424, 37, 28, 50, 438, 62],
[216, 47, 24, 50, 228, 72],
[562, 54, 23, 54, 574, 81],
[445, 63, 24, 59, 457, 93],
[217, 100, 23, 69, 229, 135],
[565, 115, 29, 65, 580, 148],
[596, 113, 22, 67, 607, 147]]

lst1 = mylst[4:6][:]

lst2 = mylst[:][4:6]

Strange thing, I get for lst1 and lst2 variables the same output:

print(lst1)
[[562, 54, 23, 54, 574, 81], [445, 63, 24, 59, 457, 93]]

print(lst2)
[[562, 54, 23, 54, 574, 81], [445, 63, 24, 59, 457, 93]]

How can be both the same?



Solution 1:[1]

When using [:], you are effectively selecting all the list, thereby making a copy of it. Here is what happens if you try to visualize it:

lst2 = mylist[:] # This is effectively creating a copy of mylist completely such that:
# mylist[:] = mylist
# then when tring to slice [4:6], you get the rows 4 and 5:
lst2[4:6] == mylist[4:6] # which is: 
                           [[562, 54, 23, 54, 574, 81], [445, 63, 24, 59, 457, 93]]

Now onto lst1:

lst1 = mylist[4:6] # Immediately gets the rows 4 and 5
                   # which is: [[562, 54, 23, 54, 574, 81], [445, 63, 24, 59, 457, 93]]
lst1 = mylist[4:6][:] # This is simply a copy of mylist[4:6]

Hence, they are both the same.

Hope this helps!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 NeuralX