Hour 8. Using Lists and Tuples
What You’ll Learn in This Hour:
Working with tuples and lists
Using multidimensional lists
Building lists with comprehensions
When you work with variables, sometimes it comes in handy to group data values together so that you
can iterate through them later in your script. You can’t easily do that with separate variables, but
Python provide a solution for you.
Most programming languages use array variables to hold multiple data values but point to them using
a single indexed variable name. Python is a little different in that it doesn’t use array variables.
Instead, it uses a couple other variable types, called lists and tuples. This hour examines how to use
lists and tuples to store and manipulate data in Python scripts.
Introducing Tuples
The tuple data type in Python allows you to store multiple data values that don’t change. In
programming-speak, these data values are said to be immutable.
After you create a tuple, you can either work with the tuple as a single object or reference each
individual data value inside the tuple in your Python script code.
The following sections walk through how to create and use tuples in your scripts.
Creating Tuples
There are four different ways to create a tuple value in Python:
Create an empty tuple value by using parentheses, as in this example:
>>> tuple1 = ()
>>> print(tuple1)
()
>>>
Add a comma after a value in an assignment, as in this example:
>>> tuple2 = 1,
>>> print(tuple2)
(1,)
>>>
Separate multiple data values with commas in an assignment, as in this example:
>>> tuple3 = 1, 2, 3, 4
>>> print(tuple3)
(1, 2, 3, 4)
>>>
Use the tuple() built-in function in Python and specify an iterable value (such as a list value,
which we’ll talk about later), as in this example:
>>> list1 = [1, 2, 3, 4]
>>> print(list1)