5a: Sequences
Table of Contents
1. Indexing strings
If you have a longer string, you may want to extract parts of it. This is done using indexing. To get a character out of a string, just write its index in square brackets.
s = "Big Tech" print(s[0]) print(s[5])
Sometimes you want to extract more than one letter at a time. In that case, you can write a start and end index, with a colon in between:
s = "Big Tech" print(s[0:5])
Just like with range, the first index is included, and the second is excluded: from [start] up to, but not including [end].
You're also allowed to leave out the start index if it is zero, or the end index if you want to go to the end of the string.
s = "Big Tech is a threat to all of us" print(s[1:])
The last item of a sequence (or the last character of a string) can be indexed with -1
:
s = "Big Tech" print(s[-1]) # and the second last (etc.) print(s[-2])
Also, just like with range, you can add a third number that will work as a step size:
s = "Big Tech is a threat to democracy" print(s[-2:0])
> How do you get all characters in even positions from the string?
s = "Big Tech is a threat to democracy" print(s[1::2])
> How can you use indexing to reverse a string?
s = "Big Tech is a threat to democracy" print(s[-1:5:-1])
Take away: negative stepsize = you flip the sequence.
for i in "hello": print(i)
for i in range(0,5): print(i)
2. Sequences: strings, ranges, tuples and lists
The string and range types are examples of a "sequence". A sequence has the following properties:
- It supports indexing
- You can ask the length of the sequence using the "len" function
- You can ask if a value is present in the sequence using "in"
- You can put it in a for loop
Python has other types that are also sequences. The two most important ones are: tuples and lists.
3. Tuples
A tuple is just a list of values. You can make a value with the type tuple by listing all the values you want to include in parentheses:
a = 5 print(a+3) t = ("Deadname", "Twitter", True)
> Ask Python for the length of this tuple
t = ("Deadname", "Twitter", True) a = (3, 10, "thingA", "thingB", False, 1.5) print(len(a))
> How do we get the third item from this tuple?
a = (3, 10, "thingA", "thingB", False, 1.5) print(a[2])
> How do we print out all the values in the tuple?
a = (3, 10, "thingA", "thingB", False, 1.5) print(a)
3.1. Basics
One nice thing about a tuple is that you can treat it as a single unit. For example, you can store a tuple with multiple values in just a single variable.
var1 = ("These", "are", 5, True, "items")
Also, a function can return only a single value, but by combining multiple values into a tuple, you can still return all of them at once.
def test(a, b, c): a = a * 2 b = b + 1 c = c / 2 return (a, b, c) print(test(1,2,3))
3.2. Converting to tuple
Just like with the types we have seen before, you can use the name of the type as a function, that will convert other values to that type. (e.g. int()
, str()
, bool()
). For tuples, that is only possible if the other value is something that could be put in a for loop itself. You then get a tuple with each value.
print(int(5.0)) print(type(str(5))) print(float("hi"))
var1 = tuple("Big Tech") print(var1)
You can put tuples inside other tuples. This works just as you might expect:
t2 = (3, (4,5), 6)
> What do you get with t2[1]?
t2 = (3, (4,5), 6) print(t2[1])
> How would you extract the 4 from t2?
t2 = (3, (4,5), 6) print(t2[1][0])
3.3. Looping through tuples!
t1 = ("this", "also", "works", "well", 100, True) for i in t1: print(i)
3.4. Trick: unpacking tuples
You can get values out of tuples by indexing.
t3 = ("sheep", "wolf", "farmer", "cabbage") object1 = t3[0] object2 = t3[1] object3 = t3[2] object4 = t3[3] (object1, object2, object3, object4) = t3 print(object4)
4. Lists
4.1. Basics
Lists are very similar to tuples, but they are a bit more flexible.
You can make them the same way you make tuples, except you have to use square brackets rather than round ones:
l = ["This", "list", "contains", "the boolean value", True, 43, 1.0] for i in l: print("----") print(i)
You can still use indexing, ask for the length, etcetera.
l = ["This", "list", "contains", "the boolean value", True] print(l[-1])
The difference is that with lists, you can actually change the values that are stored inside the list AFTER creating the list.
l = ["This", "list", "contains", "the boolean value", True] l[-1] = False print(l)
We say that a tuple is "immutable": once you create it, you cannot change it anymore.
A list, in contrast, is "mutable": after you have created it, you can adjust indivual values.
Note the difference:
# Here we simply overwrite the complete original value of tuple1. The # tuple1 that we print is completely different from the tuple1 we begin # with. tuple1 = (1, True, "Look at this") tuple1 = (2, True, "Look at this") print(tuple1) # Here we only change the first item of the list. The list1 that we # print is the same that we begin with, with one item changed. list1 = [1, True, "look at this"] list1[0] = 2 print(list1)
4.2. Why not always lists?
Why would you ever use tuples if lists are more powerful?
- Tuples can be a bit faster
- It helps your program be readable if you can tell that you don't intend to change the values in the tuple
- You can freely use tuples with sets and dictionaries, two more data types that you will learn about later, while lists have limitations.
5. Some in-class playing
You can redefine multiple items in a list at once, as long as they form a continuous slice of the list that you're editing:
l = ["hi", 4, True] l[0:1] = [False, 3] print(l)