4.5. Sequence Indexing

4.5.1. Accessing element with index

  • Index must be positive or negative int or zero

  • Index must be less or equal to length of object

  • Negative index starts from the end and go right to left

4.5.1.1. Indexing from start

text = 'We choose to go to the Moon!'

text[0]         # 'W'
text[1]         # 'e'
text[23]        # 'M'

4.5.1.2. Indexing from the end

text = 'We choose to go to the Moon!'

text[-1]        # '!'
text[-5]        # 'M'

4.5.1.3. Accessing not existing element

text = 'We choose to go to the Moon!'

text[100]
# IndexError: string index out of range

4.5.2. Indexing data structures

4.5.2.1. Indexing str

DATA = 'abcde'

DATA[2]             # 'c'
DATA[-1]            # 'e'

4.5.2.2. Indexing list

  • Indexes works the same like for str

DATA = ['a', 'b', 'c', 'd', 'e']

DATA[1]             # 'b'
DATA[-2]            # 'd'

4.5.2.3. Indexing tuple

  • Indexes works the same like for str

DATA = ('a', 'b', 'c', 'd', 'e')

DATA[1]             # 'b'
DATA[-2]            # 'd'

4.5.2.4. Indexing set

  • Indexes on set are not possible

DATA = {'a', 'b', 'c', 'd', 'e'}

DATA[1]
# TypeError: 'set' object is not subscriptable

4.5.2.5. Indexing dict

  • Indexes on dict are not possible

DATA = {
    'a': 1,
    'b': 2,
}

DATA[1]
# KeyError: 1
DATA = {
    1: 'a',
    2: 'b',
}

DATA[1]
# 'a'

4.5.3. Assignments

Todo

Create assignments