Sequences

String Indexes

Strings can be indexed and sliced just like lists:

>>> hello = "Hello world"
>>> hello[1]
'e'
>>> hello[3:8]
'lo wo'
>>> hello[-1]
'd'

Lists and strings are both sequence. Sequences can all be indexed from 0 until 1 less than their length.

What’s a sequence?

Sequences share a number of common properties.

All sequences:

  • can be indexed (and usually sliced)

  • can be looped over (more on that later)

  • have a length (via the built-in len function)

Immutability

Can we change strings?

>>> hello[4] = "a"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

If you ever see code that appears to modify a string, look closer. The code is returning a new string, not modifying the original.

>>> id(hello)
4313487792
>>> hello = hello.lower()
>>> hello
'hello world'
>>> id(hello)
4313488368
>>> hello += "!"
>>> hello
'hello world!'
>>> id(hello)
4313488368

Here we can see that each time it appears that we have modified the string hello, the variable gets a new id because Python is actually creating a new string.