Run the following lines of code one-by-one in your interactive shell, and discuss what each of them is doing.
my_list = [0,10,20,30,40,50,60,70,80,90]
print( my_list[2:7] )
print( my_list[2:] )
print( my_list[:7] )
my_string = "The quick brown fox jumps over the lazy dog"
print( my_string[12:25] )
print( my_list.index(30) )
print( my_string.index("lazy") )
lazy_index = my_string.index("lazy")
print(my_string[lazy_index:(lazy_index+4)])
This is called slicing.
Notice that my_list[start:end] gives you the slice of the list starting at index start and ending just before index end.
Recall that lists only reference their data, so when you assign, it copies the reference to the same list - you end up with two names for the same list.
x = [1,2,3,4,5]
y = x
y[2] = 9999
print(x)
print(y)
But, a slice will always be a copy, so you can make a real copy of a whole list using a slice
x = [1,2,3,4,5]
y = x[:]
y[2] = 9999
print(x)
print(y)
sequences, can use [] notation, can loop through them both, can check their length with len()
my_list = [0.0, 1.1, 42, 3.14]
my_string = "The quick brown fox jumps over the lazy dog"
print( my_list[2] )
print( my_string[2] )
work with concatenation + and repition * operators
print( my_list + [1,2,3] )
print( my_string + ", and the dog doesn't care." )
print( my_list * 3 )
print( my_string * 3 )
can process them with in, count(), and index()
print( 1.1 in my_list )
print( "fox" in my_string )
print( my_list.count(42) )
print( my_string.count("ox") )
print( my_list.index(42) )
print( my_string.index("ox") )
Before running these, discuss in your groups what you think will happen. Then, try it and see if you were right.
my_list = [0.0, 1.1, 42, 3.14]
my_list[2] = 5
print(my_list)
my_string = "The quick brown fox jumps over the lazy dog"
#my_string[2] = "y"
#print(my_string)
my_string_list = list(my_string)
print(my_string_list)
my_string_list[2] = "y"
print(my_string_list)
my_string = "".join(my_string_list)
print(my_string)
You might think that a string is just a list of characters, and that's pretty close. However, they differ in one important property:
Lists are mutable, meaning they can be changed
Strings are immutable, meaning they can't be changed
This means that with a string, you can't use any list method that changes the list
append()insert()remove()pop()We will see other examples of both mutable and immutable objects in Python.