# Sequences: Lists, Strings, and Tuples

# Learning Objectives

After completing this lesson, you will be able to:

  • Create Lists, Tuples, and ranges
  • Use indexing to access individual locations in a sequence
  • Convert between Strings and Lists
  • Iterate through sequences using for-loops

# Lesson

In the previous lesson, you learned how to store single values in memory by assigning variable names.

But when you need to keep track of many values of the same kind (e.g, book titles, favorite movies, groceries to buy), it makes more sense to create a single variable that can hold multiple values.

In this lesson, you will build a simple to-do list program that lets you:

  • Print your to-do list
  • Add items to your to-do list
  • Mark items as "complete" - removing them from the list

# What is a Sequence?

In Python, a sequence is a data type that can store multiple, individual values. Examples of sequences include:

# List
programming_languages = ["bash", "Python", "HTML", "CSS", "JavaScript", "SQL"]

# Tuple
gps_coordinates = (33.848673, -84.373313)

# range
numbers_from_zero_to_a_million = range(1000000)
1
2
3
4
5
6
7
8

Briefly, each sequence type has a specialty:

  • Lists are mutable (modifiable) sequences - versatile, general-purpose collection
  • Tuples are immutable sequences - best for representing a something with a fixed size (e.g., GPS coordinates)
  • ranges are lists of numeric values

# How do I create a List?

Lists can hold any other type (Strings, numbers, other Lists, etc.). The easiest way to create one is to assign a List literal to a variable:

todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"]
1

A List literal is:

  • one or more values (or variables)
  • separated by commas ,
  • enclosed in square brackets []

# How do I access items in a Sequence?

You can access items in a sequence in groups or individually.

# How do I access individual items in a Sequence?

Here is how Python stores values in our todos List:

index value
0 "pet the cat"
1 "go to work"
2 "feed the cat"

Python uses an integer index to identify values within a single List. The first index is always 0.

TIP

One way to think of an index is like a "seat number" on a plane, except that the seat numbers are numeric and start at 0.

You use the index to refer to a specific item in the List:

todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"]

first_item = todos[0]
second_item = todos[1]
1
2
3
4

It is not necessary to create a variable. You can index as part of an expression:

todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"]

# first_item = todos[0]
print("The first item is:", todos[0])
# second_item = todos[1]
print("The second item is:", todos[1])
1
2
3
4
5
6

# What happens if I specify an invalid index?

Python considers it an error if you use an index that falls outside the range of a sequence:

todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"]

print("This item does not exist:", todos[10])

1
2
3
4

Specifically, IndexError will be thrown:

Traceback (most recent call last):
  File "todo-2b.py", line 3, in <module>
    print("This item does not exist:", todos[10])
IndexError: list index out of range
1
2
3
4

As with any exception, you can handle it with try/except:

todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"]

try:
    print("This item does not exist:", todos[10])
except IndexError:
    print("You almost got an IndexError!")

1
2
3
4
5
6
7

Now a useful message appears instead of your program "erroring out":

You almost got an IndexError!
1

# Why is a negative index valid?

Python allows you to use a negative index, which tells it to start from the end instead of the beginning.

todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"]

print("This is the last item:", todos[-1])
print("This is the next to last item:", todos[-2])
1
2
3
4

# How do I access groups of items in a Sequence?

You can access all of the items simply by using the variable name for the sequence itself:

todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"]

print("Here are your todos:")
print(todos)
1
2
3
4

Which prints the following:

Here are your todos:
['pet the cat', 'go to work', 'feed the cat']
1
2

You can use the slicing syntax to access a subset of the items:




 

todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"]

print("Here are the second and third todos:")
print(todos[1:3])
1
2
3
4

When you slice a List, you normally provide two number separated by a :

  • The first number is the starting index. It is included in the result
  • The second number is the ending index. It is not included in the result.

If you omit the starting index, Python starts the slice at the beginning (index 0). If you omit the ending index, Python goes to the end (the last index).

todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"]

print("Slice from the third through the end:")
print(todos[2:]) # The third item is index 2

print("Slice from the beginning up to, but not including the fourth:")
print(todos[:3]) # The fourth item is index 3
1
2
3
4
5
6
7

Here is the output:

Slice from the third through the end:
['shop for groceries', 'go home', 'feed the cat']
Slice from the beginning up to, but not including the fourth:
['pet the cat', 'go to work', 'shop for groceries']
1
2
3
4

You can use negative indexes with slices:

todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"]

print("Two items up to, but not including the last:", todos[-3:-1])
print("These are the last 3 items:", todos[-3:])
1
2
3
4

Which gives the following result:

Two items up to, but not including the last: ['shop for groceries', 'go home']
These are the last 3 items: ['shop for groceries', 'go home', 'feed the cat']
1
2

# How do I iterate through a Sequence?

Now that you know how to access items manually, it is time to automate that with a loop. Using a loop to access a sequence's items one at a time is called iteration.

In this portion of the lesson, we will print the items of the to-do list.

Recall that a while loop should always move closer to some end condition so that it isn't an infinite loop.

# How do I find the length of a Sequence?

Python provides a len() function that will tell you how many items are in a Sequence.

You give len() a Sequence; it returns an integer. We will use this as part of the condition for a while-loop.



 
 


 


todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"]

index = 0 # Begin with index 0
while index < len(todos):
    todo = todos[index]
    print("%d: %s" % (index + 1, todo))
    index += 1

1
2
3
4
5
6
7
8

These are the three parts of our while loop:

  • An initial state: we start the index variable at 0
  • A condition: only run the code block if index is less than len(todos)
  • A code block that moves us closer to the end condition: index += 1

This while-loop is exactly like the simple counter program from the previous lesson. The only difference is that on line 5, we create a todo variable to reference the item at todos[index].

Not only does incrementing move us closer to the end condition, but it lets us access the next item in the list each time the code block runs.

When we run our program, we see the following:

1: pet the cat
2: go to work
3: shop for groceries
4: go home
5: feed the cat
1
2
3
4
5

On line 6 of our program, we interpolate the value index + 1 so that it prints a "human readable" version of our index.

# What is a for-loop and why should I use it with a List?

Often, you do not need to know the specific index of an item. You just want the items themselves.

Python provides another kind of loop: the for-loop. Here is our to-do printer using this syntax, with the numerical index omitted:

todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"]

for todo in todos:
    print(todo)
1
2
3
4

It's so much shorter! For-loops are a shorthand for iterating and accessing an item at a time.

pet the cat
go to work
shop for groceries
go home
feed the cat
1
2
3
4
5

If you do want to show the index (or at least number the todos) you can add a variable that you display and increment:



 


 

todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"]

count = 1
for todo in todos:
    print("%d: %s" % (count, todo))
    count += 1
1
2
3
4
5
6

Other than looking nice next to each to-do, the count variable serves no other purpose in our for-loop.

1: pet the cat
2: go to work
3: shop for groceries
4: go home
5: feed the cat
1
2
3
4
5

# How do I modify a List?

Lists are Python's mutable Sequence type, meaning that you can add, remove, and replace items.

# How do I add items to a List?

There are three ways to add items to a List:

  • You can .append() individual items
  • You can concatenate two lists together
  • You can .extend() a list using elements from another list

Each List has a .append() method that you can use like this:

todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"]

todos.append("binge watch a show")
todos.append("go to sleep")

count = 1
for todo in todos:
    print("%d: %s" % (count, todo))
    count += 1
1
2
3
4
5
6
7
8
9

You can see that it adds on to our original todos:

1: pet the cat
2: go to work
3: shop for groceries
4: go home
5: feed the cat
6: binge watch a show
7: go to sleep
1
2
3
4
5
6
7

TIP

A method is just like a function, but methods "belong to" a specific instance of a data type.

For example, every List has its own .append() method for adding on new items.

Alternatively, you can use the concatenation operator + to combine two lists:

todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"]

todos = todos + ["binge watch a show", "go to sleep"]

count = 1
for todo in todos:
    print("%d: %s" % (count, todo))
    count += 1
1
2
3
4
5
6
7
8

This is equivalent to using the .extend() method:

todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"]

todos.extend(["binge watch a show", "go to sleep"])

count = 1
for todo in todos:
    print("%d: %s" % (count, todo))
    count += 1
1
2
3
4
5
6
7
8

TIP

Concatenation produces a new List.

.append() and .extend() modify a List in-place. That is, these mutate a List instead of returning

Let's modify our to-do program, prompting the user for items to add. If the user just presses Enter, the program will exit. If they do provide a new to-do, we'll add it to the list and print their current to-do items.

TIP

Try to use what you've learned so far and implement this on your own. When you're ready, please continue with the lesson.

Creating the program loop

Our program needs to prompt the user for input until they press Enter without typing anything else. That seems like a good case for a while-loop.

In order to get our initial state, we need to prompt the user before the start of the while-loop. Then, in the body of our loop, we need to prompt them again. Since our code block must always move us closer to the end condition, we need to give the user a chance to press Enter to end the program.

Here is our program:

todos = []

# Prompt the user the first time
new_todo = input("What do you need to do? ")
while len(new_todo) > 0:
    todos.append(new_todo)

    # Print the current list of to-do items
    print("To do:")
    print("====================")
    count = 1
    for todo in todos:
        print("%d: %s" % (count, todo))
        count += 1

    # Prompt the user again
    print("\n")
    new_todo = input("What do you need to do? ")

print("Have a nice day!")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

On the last line of the program, we have a print() statement that is not part of the body of the while-loop. It runs after the while-loop has finished.

Here is an example session:

$ python3 todo-9.py 
What do you need to do? feed the cat
To do:
====================
1: feed the cat


What do you need to do? feed the cat again
To do:
====================
1: feed the cat
2: feed the cat again


What do you need to do? keep feeding the cat
To do:
====================
1: feed the cat
2: feed the cat again
3: keep feeding the cat


What do you need to do? 
Have a nice day!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# How do I replace items in a List?

You can use an index to refer to a specific place in a List. If you do this on the LHS of an assignment, you can replace an item:

todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"]

todos[1] = "go to the grocery store"
print(todos)
1
2
3
4

In this example, we have reassigned the value at index 1:

['pet the cat', 'go to the grocery store', 'shop for groceries', 'go home', 'feed the cat']
1

If you need to replace multiple items, you can use a slice on the LHS and a List on the RHS:

todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"]

todos[1:4] = ["make cat food", "cook cat food"]
print(todos)
1
2
3
4

Here, we replace the items from index 1 up to, but not including index 4:

['pet the cat', 'make cat food', 'cook cat food', 'feed the cat']
1

Notice that our slice on the LHS referred to 3 items, but the List on the RHS only contained 2 items. Python replaces that entire segment of the list with a new list; it is not replacing those items individually.

For our to-do program, we'll first prompt the user for whether they want to print their to-do list, add an item, or replace an item. Then, our program will carry out that choice.

This will be a significant change to our code, but we'll take it in steps.

TIP

Now is another opportunity to exercise your knowledge. Try implementing another while-loop around the existing loop. This loop should ask them

Wrapping our program in a main menu

Before moving on to the replace-item feature, let's make sure to prompt the user with a main menu. Then, based on that choice, we can run one of our existing procedures (printing or adding).

todos = []

# Create a constant for our main menu.
# This saves us from having to type it out twice.
MAIN_MENU = """
Choose an action:
P: Print your to-do list
A: Add a to-do item
R: Replace a to-do item

(Or press Enter to exist the program.)
"""

choice = input(MAIN_MENU)
choice = choice.upper() # Simplifies our if-conditions

# As long as they type something, keep prompting
while len(choice) > 0:
    if choice == "P":
        # Print the current list of to-do items
        print("\n\n\nTo do:")
        print("====================")
        count = 1
        for todo in todos:
            print("%d: %s" % (count, todo))
            count += 1
    elif choice == "A":
        new_todo = input("What do you need to do? ")
        if len(new_todo) > 0:
            todos.append(new_todo)
    else:
        print("\n\n***Please enter a valid menu option.***")    

    choice = input(MAIN_MENU)
    choice = choice.upper() # Simplifies our if-conditions

print("Have a nice day!")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

On line 15, we convert the user's input to upper-case. If we didn't do this, lines 19 and 27 would have to account for either the upper or lower-case version.

Here is a brief session with our program:

$ python3 todo-v2-3.py 

Choose an action:
P: Print your to-do list
A: Add a to-do item
R: Replace a to-do item

(Or press Enter to exist the program.)
p



To do:
====================

Choose an action:
P: Print your to-do list
A: Add a to-do item
R: Replace a to-do item

(Or press Enter to exist the program.)
a
What do you need to do? rock the casbah

Choose an action:
P: Print your to-do list
A: Add a to-do item
R: Replace a to-do item

(Or press Enter to exist the program.)
p



To do:
====================
1: rock the casbah

Choose an action:
P: Print your to-do list
A: Add a to-do item
R: Replace a to-do item

(Or press Enter to exist the program.)

Have a nice day!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
Replacing an item

We need to add another elif for replacing an item in the to-do list.

If the user chooses to replace an item, it is a good idea to print the to-do list so that they can see the human-readable numbers.

Then, we can prompt them for which number to replace and then prompt them for the new to-do item.































 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 








todos = []

# Create a constant for our main menu.
# This saves us from having to type it out twice.
MAIN_MENU = """
Choose an action:
P: Print your to-do list
A: Add a to-do item
R: Replace a to-do item

(Or press Enter to exist the program.)
"""

choice = input(MAIN_MENU)
choice = choice.upper() # Simplifies our if-conditions

# As long as they type something, keep prompting
while len(choice) > 0:
    if choice == "P":
        # Print the current list of to-do items
        print("\n\n\nTo do:")
        print("====================")
        count = 1
        for todo in todos:
            print("%d: %s" % (count, todo))
            count += 1
    elif choice == "A":
        new_todo = input("What do you need to do? ")
        if len(new_todo) > 0:
            todos.append(new_todo)
    elif choice == "R":
        # Print the current list of to-do items
        print("\n\n\nTo do:")
        print("====================")
        count = 1
        for todo in todos:
            print("%d: %s" % (count, todo))
            count += 1
        
        which_index = input("Which to-do number? ")
        try:
            which_index = int(which_index)
            which_index -= 1 # Convert from human-readable to 0-based index
            
            if which_index >= 0 and which_index < len(todos):
                new_todo = input("What do you need to do? ")
                todos[which_index] = new_todo
        except ValueError:
            print("\n\n***Please enter a number.***")    
    else:
        print("\n\n***Please enter a valid menu option.***")    

    choice = input(MAIN_MENU)
    choice = choice.upper() # Simplifies our if-conditions

print("Have a nice day!")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

Since our program shows human-readable numbers, we have to subtract 1 to get the corresponding List index.

WARNING

Never trust user input!

Always do appropriate error checking using try/except and if/else.

Here is a session that demonstrates replacing an item.

$ python3 todo-v2-4.py 

Choose an action:
P: Print your to-do list
A: Add a to-do item
R: Replace a to-do item

(Or press Enter to exist the program.)
a
What do you need to do? rock the casbah 

Choose an action:
P: Print your to-do list
A: Add a to-do item
R: Replace a to-do item

(Or press Enter to exist the program.)
r



To do:
====================
1: rock the casbah
Which to-do number? 1
What do you need to do? rock the catbox

Choose an action:
P: Print your to-do list
A: Add a to-do item
R: Replace a to-do item

(Or press Enter to exist the program.)

Have a nice day!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

:::

# How do I delete items from a List?

The syntax for removing an item from a List is different from what we've seen so far.

Use the del keyword to tell Python to remove one or more items from a List:

todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"]

del todos[0] # Remove the first one
print(todos)

del todos[1:3] # Remove items at index 1 up but not including index 3
print(todos)
1
2
3
4
5
6
7

Here is the output from running the example:

['go to work', 'shop for groceries', 'go home', 'feed the cat']
['go to work', 'feed the cat']
1
2

We can use this to mark an item an item as complete in our to-do program. It will require an additional choice in our main menu as well as another elif branch in our main loop.

TIP

This is the last change to our to-do program! Give it a shot before looking at the implementation.

Adding "Done" feature to our to-do program

The code for removing an item is very similar the code for replacing an item. The main difference is that instead of prompting for a new to-do, we use the del keyword to remove the item at the specified index.


















































 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 








todos = []

# Create a constant for our main menu.
# This saves us from having to type it out twice.
MAIN_MENU = """
Choose an action:
P: Print your to-do list
A: Add a to-do item
R: Replace a to-do item
C: Complete a to-do item
(Or press Enter to exist the program.)
"""

choice = input(MAIN_MENU)
choice = choice.upper() # Simplifies our if-conditions

# As long as they type something, keep prompting
while len(choice) > 0:
    if choice == "P":
        # Print the current list of to-do items
        print("\n\n\nTo do:")
        print("====================")
        count = 1
        for todo in todos:
            print("%d: %s" % (count, todo))
            count += 1
    elif choice == "A":
        new_todo = input("What do you need to do? ")
        if len(new_todo) > 0:
            todos.append(new_todo)
    elif choice == "R":
        # Print the current list of to-do items
        print("\n\n\nTo do:")
        print("====================")
        count = 1
        for todo in todos:
            print("%d: %s" % (count, todo))
            count += 1
        
        which_index = input("Which to-do number? ")
        try:
            which_index = int(which_index)
            which_index -= 1 # Convert from human-readable to 0-based index
            
            if which_index >= 0 and which_index < len(todos):
                new_todo = input("What do you need to do? ")
                todos[which_index] = new_todo
        except ValueError:
            print("\n\n***Please enter a number.***")
    elif choice == "C":
        # Print the current list of to-do items
        print("\n\n\nTo do:")
        print("====================")
        count = 1
        for todo in todos:
            print("%d: %s" % (count, todo))
            count += 1
        
        which_index = input("Which to-do number? ")
        try:
            which_index = int(which_index)
            which_index -= 1 # Convert from human-readable to 0-based index
            
            if which_index >= 0 and which_index < len(todos):
                completed_todo = todos[which_index]
                del todos[which_index]
                print("%s has been marked complete!" % completed_todo)
        except ValueError:
            print("\n\n***Please enter a number.***")
    else:
        print("\n\n***Please enter a valid menu option.***")    

    choice = input(MAIN_MENU)
    choice = choice.upper() # Simplifies our if-conditions

print("Have a nice day!")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76

Here is a session that demonstrates removing an item.

Choose an action:
P: Print your to-do list
A: Add a to-do item
R: Replace a to-do item
C: Complete a to-do item
(Or press Enter to exist the program.)
a
What do you need to do? rock the catbox

Choose an action:
P: Print your to-do list
A: Add a to-do item
R: Replace a to-do item
C: Complete a to-do item
(Or press Enter to exist the program.)
c



To do:
====================
1: rock the catbox
Which to-do number? 1
rock the catbox has been marked complete!

Choose an action:
P: Print your to-do list
A: Add a to-do item
R: Replace a to-do item
C: Complete a to-do item
(Or press Enter to exist the program.)
p



To do:
====================

Choose an action:
P: Print your to-do list
A: Add a to-do item
R: Replace a to-do item
C: Complete a to-do item
(Or press Enter to exist the program.)

Have a nice day!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

# When should I use nested loops?

Lists can hold any kind of value, including Lists.

You can use nested loops to create nested Lists and to iterate over them.

Let's create a tic-tac-toe board using nested loops. It will look like this:

Let's say you wanted to access a particular item in the nested Lists:

x

To access the item marked with an X, you have to index twice, like so:

board[1][2]
1

You read this from left to right: The board variable holds a List. board[1] refers to the item at index 1, which is also a List. This corresponds to the 2nd row.

In that 2nd row, to access the 3rd item, you use index 2

How would you access the following item?

x
Answer

The item on the 3rd row, in the 2nd column is accessed like so:

board[2][1]
1

# How do I use the range() function to generate numbers?

To create our game board, we need to produce numbers that correspond to our List indexes.

To do that, we'll use the range() function. You pass range() a number, and it returns the integers up to, but not including that number.

First, let's see the nested loops in action, just printing the numbers generated by range(0):

SIZE = 3
for y in range(SIZE):
    for x in range(SIZE):
        print(y, x)

1
2
3
4
5

Here is our output, showing the values:

0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
1
2
3
4
5
6
7
8
9

Now, instead of printing the numbers, we'll create the board as an empty List, then we'll .append() an empty List.

SIZE = 3
board = [] # Start with an empty List
for y in range(SIZE):
    # Each element in the board will also be a List
    board.append([])
    for x in range(SIZE):
        pass

print(board)
1
2
3
4
5
6
7
8
9

This results in a List of empty Lists:

[[], [], []]
1

And to complete the empty game board, we'll put the "coordinates" in each of the inner Lists. This can help us visualize how our loops are working:

SIZE = 3
board = [] # Start with an empty List
for y in range(SIZE):
    # Each element in the board will also be a List
    board.append([])        
    for x in range(SIZE):
        # Fill our inner Lists with the coordinates
        board[y].append("[%d][%d]" % (y, x))

print(board)
1
2
3
4
5
6
7
8
9
10

Here is what our game board looks like now:

[['[0][0]', '[0][1]', '[0][2]'], ['[1][0]', '[1][1]', '[1][2]'], ['[2][0]', '[2][1]', '[2][2]']]
1

# How do I print all of the items in a nested List?

We used nested loops to generate the game board, and we can use similar code to print the board.

Instead of printing the List itself, let's print it as a grid:

SIZE = 3
board = [] # Start with an empty List
for y in range(SIZE):
    # Each element in the board will also be a List
    board.append([])        
    for x in range(SIZE):
        # Fill our inner Lists with the coordinates
        board[y].append("[%d][%d]" % (y, x))

# Print the board as a grid
for row in board:
    for column in row:
        print("%s  " % column, end="")
    print("\n")
        
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

We added nested for-loops, and since we wanted the values (instead of the indexes), we did not use the range() function.

[0][0]  [0][1]  [0][2]  

[1][0]  [1][1]  [1][2]  

[2][0]  [2][1]  [2][2]  

1
2
3
4
5
6

# Making a move

Adding game play is part of the exercises after the lesson, but here is an example of placing a move on the game board:

SIZE = 3
board = [] # Start with an empty List
for y in range(SIZE):
    # Each element in the board will also be a List
    board.append([])        
    for x in range(SIZE):
        # Fill our inner Lists with the coordinates
        board[y].append("[%d][%d]" % (y, x))

# Print the board as a grid
for row in board:
    for column in row:
        print("%s  " % column, end="")
    print("\n")

print("\n\nPlayer X is moving.\n\n")
board[0][2] = "X"

# Print the board as a grid
for row in board:
    for column in row:
        print("%s  " % column, end="")
    print("\n")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

We added nested for-loops, and since we wanted the values (instead of the indexes), we did not use the range() function.

[0][0]  [0][1]  [0][2]  

[1][0]  [1][1]  [1][2]  

[2][0]  [2][1]  [2][2]  



Player X is moving.


[0][0]  [0][1]  X  

[1][0]  [1][1]  [1][2]  

[2][0]  [2][1]  [2][2]  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# How do I use Strings as Sequences?

Like Lists, you can index, slice, and get the length of Strings as if though they were Lists.

alphabet = "abcdefghijklmnopqrstuvwxyz"

print("The first letter is", alphabet[0])

print("The first three letters are", alphabet[:3])

print("Some letters in the middle are", alphabet[11:16])

print("There are %d letters in the alphabet" % len(alphabet))
1
2
3
4
5
6
7
8
9

And the results of running the code:

The first letter is a
The first three letters are abc
Some letters in the middle are lmnop
There are 26 letters in the alphabet
1
2
3
4

# How do I loop through the characters of a String?

Because you can index and get the length of a String, you can also iterate through the individual characters:

alphabet = "abcdefghijklmnopqrstuvwxyz"

for letter in alphabet:
    print(letter)
1
2
3
4

And the results of running the code:

a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

# How do I convert a String into a List?

One notable difference between Strings and Lists is that you cannot modify a String by reassigning to an index.

alphabet = "abcdefghijklmnopqrstuvwxyz"

alphabet[0] = "4" # Uh oh.
1
2
3

This results in an error:

Traceback (most recent call last):
  File "string-2.py", line 3, in <module>
    alphabet[0] = "4" # Uh oh.
TypeError: 'str' object does not support item assignment
1
2
3
4

You would first have to convert it to a List so that you could mutate the data:

alphabet = "abcdefghijklmnopqrstuvwxyz"

alphalist = list(alphabet)
alphalist[0] = "4"

print(alphalist)
1
2
3
4
5
6

This allows you to make whatever modifications you choose:

['4', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
1

# How do I convert a List into a String?

There is a trick to converting your List back into a String, and it is a bit counter-intuitive at first.

alphabet = "abcdefghijklmnopqrstuvwxyz"

alphalist = list(alphabet)
alphalist[0] = "4"

print(alphalist)

alphabet = "".join(alphalist)
print(alphabet)
1
2
3
4
5
6
7
8
9

You use the String method .join() to reconnect the items of a List.

Because we used an empty String ("") to join the items, the resulting String has no spaces:

['4', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
4bcdefghijklmnopqrstuvwxyz
1
2

TIP

Note that we did not mutate our String, but did reassign the variable name alphabet to our newly .join()ed String.

But, we can use any String we want to insert between the joined List items:

alphabet = "abcdefghijklmnopqrstuvwxyz"

alphalist = list(alphabet)
alphalist[0] = "4"

print(alphalist)

alphabet = "!\n".join(alphalist)
print(alphabet)
1
2
3
4
5
6
7
8
9

Now, our alphabet String has an ! and a line break between each letter:

['4', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
4!
b!
c!
d!
e!
f!
g!
h!
i!
j!
k!
l!
m!
n!
o!
p!
q!
r!
s!
t!
u!
v!
w!
x!
y!
z
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

Note that .join() inserts a String between each List item. The z does not have a ! after it.

# What Sequence operations work with Tuples?

Just as with Strings, you can index, slice, and get the length of a Tuple. But you cannot modify a Tuple.

coordinates = (33.848673, -84.373313)

latitude = coordinates[0]
longitude = coordinates[1]

print("The latitude is %f and the longitude is %f" % (latitude, longitude))
1
2
3
4
5
6

This program prints the following:

The latitude is 33.848673 and the longitude is -84.373313
1

TIP

Python supports unpacking syntax which allows you to assign multiple variables at a time when used with Sequences on the RHS:

coordinates = (33.848673, -84.373313)

latitude, longitude = coordinates

print("The latitude is %f and the longitude is %f" % (latitude, longitude))
1
2
3
4
5

Tuples are immutable:

coordinates = (33.848673, -84.373313)

coordinates[0] = 40.741895
1
2
3

Assigning to an index of a Tuple results in an error:

Traceback (most recent call last):
  File "tuple-2.py", line 3, in <module>
    coordinates[0] = 40.741895
TypeError: 'tuple' object does not support item assignment
1
2
3
4

But you can concatenate to produce a new Tuple:

band_mates = ("John", "Paul", "George", "Pete")
print(band_mates)

band_mates = band_mates[:-1] # All but the last
print(band_mates)

band_mates = band_mates + ("Ringo", )
print(band_mates)
1
2
3
4
5
6
7
8

This works because you are doing reassignment, not mutation.

('John', 'Paul', 'George', 'Pete')
('John', 'Paul', 'George')
('John', 'Paul', 'George', 'Ringo')
1
2
3

TIP

To create a Tuple with a single item, you must wrap it in parentheses and add a trailing comma as shown in the previous code sample.

# Summary

In this lesson, you learned about the following Sequence types:

  • Lists
  • Strings
  • Tuples
  • ranges

Sequences in Python share a number of qualities in common. They are all:

  • index-able
  • slice-able
  • length-able

Because of these qualities, they are also iterable (meaning you can use a for-loop with them.)

# Training Exercises

# Small

# 1. Sum the Numbers

Create a list of numbers, print their sum.

# 2. Largest Number

Create a list of numbers, print the largest of the numbers.

# 3. Smallest Number

Create a list of numbers, print the smallest of the numbers.

# 4. Even Numbers

Create a list of numbers, print each number in the list that is even.

# 5. Positive Numbers

Create a list of numbers, print each number in the list that is greater than zero.

# 6. Positive Numbers II

Create a list of numbers, create a new list which contains every number in the given list which is positive.

# 7. Multiply a list

Create a list of numbers, and a single factor (also a number), create a new list consisting of each of the numbers in the first list multiplied by the factor. Print this list.

# 8. Reverse a String

Given a string, print the string reversed.

# Medium

# 1. Multiply Vectors

Given two lists of numbers of the same length, create a new list by multiplying the pairs of numbers in corresponding positions in the two lists. Example:

[2, 4, 5] x [2, 3, 6] = [4, 12, 30]
1

# 2. Matrix Addition

Given two two-dimensional lists of numbers of the size 2x2 two dimensional list is represented as an list of lists:

[ [2, -2],
   [5, 3] ]
1
2

Calculate the result of adding the two matrices. The number in each position in the resulting matrix should be the sum of the numbers in the corresponding addend matrices. Example: to add

1 3
2 4
1
2

and

5 2
1 0
1
2

results in

6 5
3 4
1
2

# 3. Matrix Addition II

Use your solution in Matrix Addition, and extend it to work for a pair of matrices of any size, as long as they have the same size.

# 4. De-dup

Given a list of numbers or strings, create a new list containing the same elements as the first list, except with any duplicate values removed. Print the list.

# 5. Leetspeak

Given a paragraph of text as a String, print the paragraph in leetspeak.

To translate a String to leetspeak, you need to replace make the following character replacements (treat all input characters as uppercase):

Letter Translates To
A 4
E 3
G 6
I 1
O 0
S 5
T 7

Example: If your program is given the String "I am a leet programmer", it should print "1 4m 4 l337 pr0gr4mm3r" as the leetspeak translation

# 6. Long-long Vowels

Given a word as a string, print the result of extending any long vowels to the length of 5.

Examples:

Good => Goooood
Cheese => Cheeeeese
Man => Man
Spoon => Spooooon
1
2
3
4

# 7. Caesar Cipher

Given a string, print the Caesar Cipher (or ROT13) of that string. What is Caesar Cipher? Learn about it here.

Use your solution to decipher the following text: "lbh zhfg hayrnea jung lbh unir yrnearq"

# Large

# 1. Tic-Tac-Toe

Continue the Tic-Tac-Toe example from the nested for-loop example

# 2. Matrix Multiplication

Given two two-dimensional lists of numbers of the size 2x2 - calculate the result of multiplying the two matrices. Print the resulting matrix.

How do you multiple two matricies?

For more information, go to this video on khanacademy.

# Interview Questions

# Fundamentals

# Bugfix

# Concepts

# Architecture

# Additional Resources

Testing for membership

You can use either the in operator or the .find() method when working with Sequences. Find out more in this blog post.

Implementing stacks and queues with .push(), .pop(), .shift(), and .unshift()

Python's List type also includes methods that let you use them like other pdata structures such as stacks and queues.

Check out this article to learn more about these classic data structures and how to implement them with Python's List type.