Lecture 9 Slides - Sequences of Data

1 of 11

Sequences of Data

CS 110

2 of 11

Sequences: Why are they useful?

  • Allows us to store collections of data and allow us to easily read and process data via loops

  • Examples:
    • A sequence of notes for creating songs
    • A sequence of colors to make a color palette
    • A pair of coordinates (x,y)
    • A sequence of coordinates to draw shapes (points, lines, polygons)
    • A sequence of canvas objects that you can move and interact with
    • ...

2

3 of 11

4 of 11

New Data Type (class): Tuple

  • A tuple is an immutable sequence of values.
  • Useful for organizing and conveniently accessing related data.
  • In Python we define them like this:

tuple_of_strings = ("first year", "sophomore", "junior", "senior")

4

5 of 11

New Data Type: Tuple

  • A tuple is an immutable sequence of values.
  • Useful for organizing and conveniently accessing related data.
  • In Python we define them like this:

tuple_of_strings = ("first year", "sophomore", "junior", "senior")

5

6 of 11

New Data Type: Tuple

  • A tuple is an immutable sequence of values.
  • Useful for organizing and conveniently accessing related data.
  • In Python we define them like this:

tuple_of_strings = ("first year", "sophomore", "junior", "senior")

6

7 of 11

Tuples: The Rules

A tuple is an immutable sequence of values:�

empty_tuple = ()

tuple_of_strings = ("first year", "sophomore", "junior", "senior")

  • The items in a tuple can be of any type
  • A tuple can be of any length
  • You can access any tuple element through 0-based indexing
  • You can slice tuples
  • You cannot edit tuples (immutability)
  • You can concatenate tuples to create new, longer tuples

7

8 of 11

What's the deal with…

immutability?

9 of 11

Data Types: Lists and Tuples

A list is a mutable sequence of values:�

empty_list = []

list_of_strings = ["first year", "sophomore", "junior", "senior"]

A tuple is an immutable sequence of values:�

empty_tuple = ()

tuple_of_strings = ("first year", "sophomore", "junior", "senior")

9

10 of 11

Lists: The Rules

A list is a mutable sequence of values:�

empty_list = []

list_of_strings = ["first year", "sophomore", "junior", "senior"]

  • The items in a list can be of any type
  • A list can be of any length
  • You can access any list element through 0-based indexing
  • You can slice a list
  • You can edit a list (mutable)
  • You can concatenate lists using the + operator
  • You can sort lists (as long as Python knows how to sort your data)
  • You can add elements to a list using the append function
  • You can remove elements in a list using the pop function
  • You can update specific elements in a list using the offset notation from #3.

11 of 11

Challenge Problem (03_quote_of_the_day.py)

See the file for details! (solution in the solutions folder)