Slicing Strings

>>> my_string = "Hello there"
>>> my_string[1:5]
'ello'
>>> my_string[2]
'l'

Slicing Lists

>>> my_list = list(range(1,6))
>>> my_list
[1, 2, 3, 4, 5]
>>> my_list[1:3]
[2,3]
>>> my_list[2]
3

[start:stop]

>>> my_list[0:2]
[1,2]
>>> my_list[2:len(my_list)]
[3,4,5]
>>> my_list[2:]
[3,4,5]
>>> my_list[:2]
[1,2]
>>> my_list[:]
[1,2,3,4,5]

Copy Lists with [:] Slice

Unlike objects from other data types, Lists and Dictionaries are mutable objects and assign one to another variable makes 2 copies that point to the same value in the memory. Use slicing to assign a copy of the list to a new variable.

>>> my_new_list = [4,2,1,3,5]
>>> my_new_list.sort()
>>> my_new_list 
[1,2,3,4,5]
>>> my_new_list = [4,2,1,3,5]
>>> my_sorted_list = my_new_list[:]
>>> my_sorted_list.sort()
>>> my_sorted_list 
[1,2,3,4,5]
>>> my_new_list
[4,2,1,3,5]