Tuples, Sets, Dictionaries

4. Tuples, Sets, Dictionaries#

There are in total four built-in collection data types in Python:

  • Lists are ordered, changeable and allow duplicate values.

  • Tuples are ordered, unchangeable and allow duplicate values.

  • Sets are unordered, unchangeable, unindexed and allow no duplicate values.

  • Dictionaries are ordered, changeable and allow no duplicate values.

You already learned about Lists. In this section you will learn about the other three types, their differences and applications.

4.1. Tuples#

A tuple is a collection of values defined by pair of parentheses ( ), separated by commas or by using the tuple() function. Items in a tuple are ordered, unchangeable, and allow duplicate values. A tuple can contain different data types. Here are some examples:

tuple_1= (0, 10 ,20, 30) # or: tuple_1= 0, 10 ,20, 30

tuple_2= "Jolie", 5, 2.5

tuple_3= tuple(["apple", "banana", "cherry"])

tuple_4= 4.5, # or tuple_4=4.5, but not tuple_4= (4.5)

print(tuple_4)
print(tuple_3)
(4.5,)
('apple', 'banana', 'cherry')

Although tuples seem similar to lists, they are often used in different situations and for different purposes. Unlike lists, the items in a tuple are immutable (or unchangeable) and usually heterogeneous (of different types).

student_info= ("Yanbin Li", "A", 8.7)

student_info[2]=24
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[2], line 3
      1 student_info= ("Yanbin Li", "A", 8.7)
----> 3 student_info[2]=24

TypeError: 'tuple' object does not support item assignment

Unpacking We can access the items in a tuple by unpacking it. Note that the number of variables on the left side of the equal sign should be equal to the number of items in the sequence.

student_info= ("Yanbin Li", "A", 8.7)    # packing
name_i,group_i,grade_i= student_info     # unpacking

print(grade_i)

Indexing, slicing and many other more operations on tuples are done in the same way as in lists. Below are some examples:

tuple_1= (0, 10 ,20, 30, 40, 50)

print(tuple_1[0:2])
print(tuple_1[-1])

4.2. Sets#

A set is an unordered collection with no duplicate elements. The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set. Sets are also used for eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.

You can Define a Set by using curly brackets {} or the set() function.

shopping_set = {'apple', 'cherry', 'tomato', 'orange', 'tomato'}

print(shopping_set) # duplicates have been removed

# fast membership testing
print( 'orange' in shopping_set )

# fast membership testing
print( 'cucumber' in shopping_set )
A={0,1,2,3,4,5,6,7,8,9}
B={0,2,4,6,8,}

print(A-B)
print(A.intersection(B)) #or A&B
print(A&B)

Here are some functions that can be used with sets (and some other collection data types).

Function

Description

add()

Adds an element to the set

copy()

Returns a copy of the set

remove()

Removes an element from the set

pop()

Removes and returns an arbitrary set element

clear()

Removes all elements from the set

4.3. Dictionaries#

Dictionary is another useful data type which allows storing data as a set of key: value pairs, allowing the collection to be indexed by the keys. Below are some examples of creating dictionaries.

dict_1 = {1: 'hello', 2: 'world'}

dict_2 = {
  "brand": "Ford",
  "electric": False,
  "year": 1964,
  "colors": ["red", "white", "blue"]
}

dict_3 = dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])

print(dict_3)

Accessing the values in a dictionary is done by using keys. Keys can be used either inside square brackets [] or with the get() method:

# using []
print(dict_3['sape'])
# using get()
print(dict_2.get('year'))

Changing a dictionary: you can change, add and remove values in a dictionary.

dict_1 = {1: 'hello', 2: 'world', 3: 'welcome', 4: 'to'}

# changing an item
dict_1[1]= 'Hi'

# adding an item
dict_1[5]= 'Python'

# removing an item using del
del dict_1[2]

# removing an item using pop
dict_1.pop(4)

print(dict_1)

Dictionary comprehension: similar to list comprehension, we can use dictionary comprehensions to create dictionaries from arbitrary key and value expressions:

dict_4= {x: x**2 for x in (2, 4, 6)}
print(dict_4)

We can loop through dictionaries and retrieve key and corresponding value at the same by using the items() method.

dict_2 = {"brand": "Ford","electric": False,"year": 1964,"colors": ["red", "white", "blue"]}
for k, v in dict_2.items():
  print(k," is ", v,".")