Python - Sequences


This lesson covers the following topics:


Sequences


In Python, a sequence is the generic term for an ordered set. There are several types of sequences in Python, the most important being strings, tuples, and lists. The location of each element within a sequence is called its index.

Software Development Cycle


Furthermore, some sequences are immutable (strings & tuples) and others are mutable (lists).

  • Immutable - means you can't change individual elements within the sequence.

  • Mutable - means you can change individual elements within the sequence.


Strings


Strings are a special type of immutable sequence within Python that can only store characters. You can think of a string as a tuple where every element is a single character. Notice that we use quotes (double or single) to define a string.

In [1]:
myString = "hello world"

In memory, the string above is a sequence of characters that looks like: String Sequence Representation

Tuples


Tuples are a type of immutable sequence within Python that can store any data-type as its elements. However, since they are immutable, once they are defined, you cannot change any of the individual elements within that sequence. Notice that we use parenthesis to define a tuple.

In [2]:
myTuple = (1, 2, 3, 123, "Hello", True)

In memory, the tuple above is a sequence of elements that looks like: Tuple Sequence Representation

Lists


Lists are a type of mutable sequence within Python that can store any data-type as its elements. Additionally, since they are mutable, you can change any of the individual elements within the sequence, even after it is initially defined. Notice that we use box-brackets to define a list.

In [3]:
myList = [1, 2, 3, 123, "Hello", True]

In memory, the list above is a sequence of elements that looks like: List Sequence Representation


Operations & Useful Functions


Below are some operations that all sequences have in common. Please note that although I'm specifically using tuples and lists for some of these examples, you can use strings, tuples, or lists for any of them and it will yield the same effect.

Operation Notes Example Output
+ Concatenates (joins) two sequences. (1, 2) + (3, 4) (1, 2, 3, 4)
* Repeats a sequence a number of times. 3 * (1, 2) (1, 2, 1, 2, 1, 2)
in Returns True/False if an element is in a sequence. 'a' in ['a', 'b', 'c'] True
mySeq[i] Returns the element of the sequence at index i.
*Left to right, the first element starts at index 0.
*Right to left, the last element starts at index -1.
mySeq = ['x', 'y', 'z']
mySeq[1]
mySeq[-1]

'y'
'z'
mySeq[i:j] Returns a slice of the sequence, starting at element
i and ending at element j (not including j).
*If i is left blank, it will start at the beginning.
*If j is left blank, it will go until the end.
mySeq = [9, 8, 7, 6, 5, 4]
mySeq[2:5]
mySeq[:2]
mySeq[:]

[7, 6, 5]
[9, 8]
[9, 8, 7, 6, 5, 4]
len(mySeq) Returns the length of a sequence (# of elements). mySeq = ['a', 'b', 'c']
len(mySeq)

3


Below are some operations that are specific to lists, due to them be mutable, which means you can change elements within the list.
(strings and tuples are immutable, so they lack this functionality)

Operation Notes Example Output
myList[i] = e Sets the value at index i to the value e. myList = ['a', 'b', 'c']
myList[0] = 1
print(myList)


[1, 'b', 'c']
myList.append(e) Adds element e to the end of the list. myList = ['a', 'b', 'c']
myList.append('d')
print(myList)


['a', 'b', 'c', 'd']
myList.clear() Removes all elements from a list. myList = ['a', 'b', 'c']
myList.clear()
print(myList)


[]
myList.index(e) Returns the index of the first occurence of e. myList = ['a', 'b', 'c', 'b']
myList.index('b')

1
myList.insert(e, i) Inserts element e at index i. All other
elements get pushed back one position.
myList = ['a', 'b', 'c']
myList.insert(True, 1)
print(myList)


['a', True, 'b', 'c']
myList.pop(i) Removes (and returns) the element at index i. myList = ['a', 'b', 'c']
myList.pop(0)
print(myList)

'a'
['b', 'c']
myList.remove(e) Removes first occurrence of element e. myList = ['a', 'b', 'c', 'b']
myList.remove('b')
print(myList)


['a', 'c', 'b']
myList.reverse() Reverses the order of a list. myList = ['a', 'b', 'c', 'd']
myList.reverse()
print(myList)


['d', 'c', 'b', 'a']
myList.sort() Sorts a list (ascending by default). myList = [3, 1, 4, 2]
myList.sort()
print(myList)


[1, 2, 3, 4]


Traversing Sequences


It is very common to iterate through a sequence in order to investigate the value of each element. This is called "traversing a sequence" and we use a for loop to do this, along with the "in" keyword.

In [4]:
# Here is an example of using the index to iterate through a sequence.
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

myString = "Simplicity is the ultimate sophistication. – Leonardo da Vinci"

for i in range(len(myString)):
    if myString[i] == 'i':
        print(f"Found an 'i' at index {i}.")

print("The loop has terminated.")
Found an 'i' at index 1.
Found an 'i' at index 5.
Found an 'i' at index 7.
Found an 'i' at index 11.
Found an 'i' at index 21.
Found an 'i' at index 31.
Found an 'i' at index 34.
Found an 'i' at index 38.
Found an 'i' at index 58.
Found an 'i' at index 61.
The loop has terminated.
In [5]:
# Here is an example of an "enhanced for loop", where the iterator variable will be the VALUE of each element,
# as opposed to the INDEX. (we lose a little information with this method)
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

myTuple = (0, 5, 7, 5, 7, 1, 5, 0, 9, 2, 7, 9, 6, 2, 7, 3, 6, 7, 7, 5)

for value in myTuple:
    if value == 2:
        print("I found a 2, but I can't tell you what index it's at.")

print("The loop has terminated.")
I found a 2, but I can't tell you what index it's at.
I found a 2, but I can't tell you what index it's at.
The loop has terminated.


Examples


In [6]:
# This example traverses a famous quote and counts the total words and composite words in the quote.
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

quote = "One day the people that don’t even believe in you will tell everyone how they met you."
author = "Johnny Depp"

words = 1
composite = 0

for letter in quote:
    if letter == " ":
        words += 1
    if letter == "’":
        composite += 1

print(f"This quote has {words} total word(s) in it and {composite} composite word(s).")
This quote has 17 total word(s) in it and 1 composite word(s).
In [7]:
# This example creates a list of 20 random numbers in the range from 0 to 100 (inclusive),
# then looks for the value of 42 within the list.
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

import random

randomNumbers = []

for i in range(20):
    num = random.randrange(1, 101)
    randomNumbers.append(num)
    
print(randomNumbers)

for i in range(len(randomNumbers)):
    if randomNumbers[i] == 42:
        print(f"Found a 42 at index {i}.")
[20, 61, 94, 95, 42, 15, 43, 56, 60, 95, 47, 8, 23, 6, 42, 89, 57, 7, 51, 22]
Found a 42 at index 4.
Found a 42 at index 14.
In [8]:
# This example takes a tuple of numeric codes that represent items in a game
# and builds a new tuple based on the values.
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

gameCodes = (3, 1, 0, 2, 0, 0, 2, 3, 0, 0, 2, 0, 3, 3)
gameSprites = ()

for i in range(len(gameCodes)):
    if gameCodes[i] == 0:
        gameSprites += ("Grass",)
    elif gameCodes[i] == 1:
        gameSprites += ("Hero",)
    elif gameCodes[i] == 2:
        gameSprites += ("Enemy",)
    elif gameCodes[i] == 3:
        gameSprites += ("Tree",)
        
print(gameSprites)
('Tree', 'Hero', 'Grass', 'Enemy', 'Grass', 'Grass', 'Enemy', 'Tree', 'Grass', 'Grass', 'Enemy', 'Grass', 'Tree', 'Tree')