[1, 2, 3, 4]
>>> tuple4 = tuple(list1)
>>> print(tuple4)
(1, 2, 3, 4)
>>>
As you may have noticed in these examples, Python denotes the tuple by grouping the data values
using parentheses.
You’re not limited to storing numeric values in tuples. You can also store string values:
Click here to view code image
>>> tuple5 = "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday"
>>> print(tuple5)
('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',
'Saturday')
>>>
You can use either single or double quotes to delineate the string values (see Hour 10, “Working with
Strings”).
Watch Out!: Tuples Are Permanent
Once you create a tuple, you can’t change the data values, nor can you add or delete
data values.
Accessing Data in Tuples
After you create a tuple, most likely you’ll want to be able to access the data values you stored in it.
To do that, you need to use an index.
An index points to an individual data value location within a tuple variable. You use the index value
to retrieve a specific data value stored in the tuple from other Python statements in your scripts.
The index value 0 references the first data value you stored in the tuple. Starting at 0 can be
confusing, so be careful when trying to reference the data values! Here’s an example:
>>> tuple6 = (1, 2, 3, 4)
>>> print(tuple6[0])
1
>>>
To reference a specific index in the tuple variable, you just place square brackets around the index
value and add it to the end of the tuple variable name.
If you try to reference an index value that doesn’t exist, Python produces an error, like this:
Click here to view code image
>>> print(tuple6[5])
Traceback (most recent call last):
File "<pyshell#33>", line 1, in <module>
print(tuple6[5])
IndexError: tuple index out of range
>>>
Accessing a Range of Values