Sequence Types: Strings, Tuples and Lists

Overview

Teaching: 10 min
Exercises: 5 min
Questions
  • What is a sequence in Python?

  • What is the difference between strings, tuples, and lists?

  • How can we access items in a sequence?

Objectives
  • Explain the features of strings, tuples, and lists.

  • Determine when to use strings, tuples, or lists to store data.

  • Access specific items in a sequence by position.

What is a sequence?

Strings

my_string = 'a sequence of characters'
my_string = "a sequence of characters"
my_string = '''a sequence of characters'''
single_quote_string = 'a string on one line'
triple_quote_string = '''a string
on two lines'''
string_from_int = str(25)
print(string_from_int)
'25'

Can you + and * strings?

What do you expect the value of full_name to be here?

first_name = 'John'
last_name = 'Smith'

full_name = first_name + ' ' + last_name

Solution

'John Smith'
  • Adding two strings joins them together
  • This is called concatenation

What does '3' * 10 produce? Is it what you expect? What about '3' * '10'?

Solution

  • '3' * 10 = '3333333333'
  • '3' * '10' gives a TypeError
  • Multiplying a string an integer N concatenates N copies of the string
  • Multiplying a string by a string is not allowed

Lists

A list stores many values in a single structure.

teen_primes = [12, 13, 17, 23]

Appending items to a list lengthens it.

primes = [2, 3, 5]
print('primes is initially:', primes)
primes.append(7)
primes.append(9)
print('primes has become:', primes)
primes is initially: [2, 3, 5]
primes has become: [2, 3, 5, 7, 9]
teen_primes = [11, 13, 17, 19]
middle_aged_primes = [37, 41, 43, 47]
print('primes is currently:', primes)
primes.extend(teen_primes)
print('primes has now become:', primes)
primes.append(middle_aged_primes)
print('primes has finally become:', primes)
primes is currently: [2, 3, 5, 7, 9]
primes has now become: [2, 3, 5, 7, 9, 11, 13, 17, 19]
primes has finally become: [2, 3, 5, 7, 9, 11, 13, 17, 19, [37, 41, 43, 47]]

Note that while extend maintains the “flat” structure of the list, appending a list to a list makes the result two-dimensional.

The empty list contains no values.

Lists may contain values of different types.

goals = [1, 'Create lists.', 2, 'Extract items from lists.', 3, 'Modify lists.']

From Strings to Lists and Back

Given this:

print('string to list:', list('tin'))
print('list to string:', ''.join(['g', 'o', 'l', 'd']))
['t', 'i', 'n']
'gold'
  1. Explain in simple terms what list('some string') does.
  2. What does '-'.join(['x', 'y']) generate?

Tuples

Tuples are “immutable” lists

 first_name = "John"
 last_name = "Smith"
 full_name = (first_name, last_name)
 print(full_name)
 ('John', 'Smith')

Accessing items in a sequence

Use an index to get a single object from a sequence.

first_name = "John"
print(first_name[0])

full_name = ("John", "A", "Doe")
middle_initial = full_name[1]
print(middle_initial)

swc_instructors = ["Matt Garcia", "Kalin Kiesling", "Taylor Scott", "Patrick Shirwise"]
an_instructor = swc_instructors[2]
print(an_instructor)
J
A.
Taylor Scott

Negative indices count backwards

print(first_name[-1])
n

Use the index to change an element of a list

small_primes = [2, 3, 5, 8, 9, 11]
print(small_primes)

small_primes[3] = 7
print(small_primes)
[2, 3, 5, 8, 9, 11]
[2, 3, 5, 7, 9, 11]

Use del operator to remove an element from a list

print(small_primes)
del small_primes[4]
print(small_primes)
[2, 3, 5, 7, 9, 11]
[2, 3, 5, 7, 11]

Strings and tuples are immutable.

element = 'carbon'
element[0] = 'C'
TypeError: 'str' object does not support item assignment

Use a slice to get part of a selection.

print(first_name[0:2])
Jo

Exercise

What does the following program print?

 atom_name = 'carbon'
 print('atom_name[1:3] is:', atom_name[1:3])
 atom_name[1:3] is: ar
  1. What does thing[low:high] do?
  2. What does thing[low:] (without a value after the colon) do?
  3. What does thing[:high] (without a value before the colon) do?
  4. What does thing[:] (just a colon) do?
  5. What does thing[number:negative-number] do?

Challenge

If you assign a = 123, what happens if you try to get the second digit of a?

Solution

Numbers are not stored in the written representation, so they can’t be treated like strings.

a = 123
print(a[1])
TypeError: 'int' object is not subscriptable

Last Character of a String

Challenge

We’ve seen one way to get the last character of a string. If Python starts counting from zero, and len returns the number of characters in a string, what is another index expression that will get the last character in the string name? Why might you prefer one over the other?

Solution

name[len(name) - 1]

Key Points

  • Strings, tuples, and lists are ordered collections of objects.

  • Strings and tuples are immutable.

  • Lists are mutable.

  • Strings are sequences of characters.

  • Tuples and lists can be of arbitrary (mixed) data types.

  • Unordered data types return data in a random order.

  • Access a specific item by its index with sequence[index].

  • Access a range of items using slices: sequence[start:stop:skip].