What does this notation do for lists in Python: "someList[:]"? What does this notation do for lists in Python: "someList[:]"? python python

What does this notation do for lists in Python: "someList[:]"?


[:] creates a slice, usually used to get just a part of a list. Without any minimum/maximum index given, it creates a copy of the entire list. Here's a Python session demonstrating it:

>>> a = [1,2,3]>>> b1 = a>>> b2 = a[:]>>> b1.append(50)>>> b2.append(51)>>> a[1, 2, 3, 50]>>> b1[1, 2, 3, 50]>>> b2[1, 2, 3, 51]

Note how appending to b1 also appended the value to a. Appending to b2 however did not modify a, i.e. b2 is a copy.


In python, when you do a = b, a doesn't take the value of b, but references the same value referenced by b. To see this, make:

>>> a = {'Test': 42}>>> b = a>>> b['Test'] = 24

What is now the value of a?

>>> a['Test']24

It's similar with lists, so we must find a way to really copy a list, and not make a reference to it. One way could be to recreate the list copy = list(list1), or use the functions of the copy module. But, after all, the easiest way, the prettiest, the best way ( ;) ) for doing this, is to copy each value of the first list to the other, by doing copy = list1[:]. It uses the slices, here list1 is sliced from index 0 to index len(list1), so the whole list1 is returned!

Moreover, the slice method is slightly faster: using the time.clock() method to measure the mean execution time of 1000 assignment of lists, each one containing 10000 random integers, with slices, constructor and deepcopy, the results show that the slices are 15% faster than the constructor method, and deepcopy is 4 times slower. However, this gain of time is negligible while using small lists: thus, using copy = list(list_to_copy) or copy = list_to_copy[:] is up to the developer's preferences.

Finally, we often forget the list.copy method, which seems to be the faster! In fact, it's even 13% faster than the slice method!


To create a copy of a list instead of passing by reference, as Python does. Use next two example to understand the difference.

Example:

# Passing by referenceSomeListA = [1, 2, 3]SomeListB = [2, 3, 4]SomeListB = SomeListASomeListA[2] = 5print SomeListBprint SomeListA# Using sliceSomeListA = [1, 2, 3]SomeListB = [2, 3, 4]SomeListB = SomeListA[:]SomeListA[2] = 5print SomeListBprint SomeListA