Other Linear Array Structures in Python#
In addition to lists, Python includes two other data structures that function as linear arrays.
Tuples#
“Tuples are used to store multiple items in a single variable…A tuple is a collection which is ordered and unchangeable. Tuples are written with round brackets…and allow duplicate values” (W3Schools, Python Tuples)
Python Examples#
We can create a tuple in Python using the round bracket syntax (()) or the tuple() method.
# creating a tuple using round brackets
sample = ("apple", "banana", "blueberry")
# checking data type
type(sample)
# creating tuple using tuple method
sample = tuple(("apple", "banana", "blueberry"))
# check data type
type(sample)
Tuple Methods#
Some of the methods we’ve already seen for lists and strings can also be used with tuples.
# return number of items in tuple
len(sample)
# access first item in tuple
sample[0]
# count number of times specific value appears in tuple
sample.count("apple")
# return index for specific value
sample.index("pear")
Note
The last line of code will return an error because peach does not appear in this tuple.
Additional Resources
For more on tuples in Python:
Allen Downey, Chapter 12 “Tuples” in Think Python: How To Think Like a Computer Scientist (O’Reilly, 2016): 139-150.
Sets#

A set is an unordered collection of unique objects. Sets are primarily used to see if an object or value is in the collection (membership). Python supports a number of set operations, but one of the primary uses is to test for membership.
Python Examples#
We can use the in operator to test for membership with a set.
# create a set
s = set([0,1,2])
# show set values
s
# test if 0 is in s
0 in s # returns true
# test if 7 is in s
7 in s # returns false
Set Methods#
We can add items to our set using .add() or remove them using .remove().
# add values to set
s.add(3)
s.add(4)
s.add(5)
# show new set with values
s
# remove 1 number value from set
s.remove(5)
# show updated set
s