Introduction to Python for Developers
George Boorman
Curriculum Manager, DataCamp
Contain unique data
Unchangeable*
Ideal to identify and remove duplicates
Quick to search (compared to other data structures such as lists)
{}
:
= Dictionary:
= Set# Create an attendee set
attendees_set = {"John Smith", "Alan Jones", "Roger Thompson",
"John Smith", "Brandon Sharp", "Sam Washington"}
print(attendees_set)
{'Alan Jones', 'Brandon Sharp', 'John Smith',
'Roger Thompson', 'Sam Washington'}
# Existing list variable attendees_list = ["John Smith", "Alan Jones", "Roger Thompson", "John Smith", "Brandon Sharp", "Sam Washington"]
# Convert to a set attendees_set = set(attendees_list)
# Check the data type type(attendees_set)
set
print(attendees_set)
{'Sam Washington', 'Roger Thompson', 'Alan Jones', 'John Smith', 'Brandon Sharp'}
[]
# Trying to subset a set
attendees_set[0]
TypeError: 'set' object is not subscriptable
attendees_set = {"John Smith", "Alan Jones", "Roger Thompson", "John Smith", "Brandon Sharp", "Sam Washington"}
# Sorting a set sorted(attendees_set)
['Alan Jones', 'Brandon Sharp', 'John Smith', 'Roger Thompson', 'Sam Washington']
sorted()
returns a list
[0]
# Creating a tuple office_locations = ("New York City", "London", "Leuven")
# Convert another data structure to a tuple attendees = tuple(attendees_list)
# Access the second element
office_locations[1]
"London"
Data structure | Syntax | Immutable | Allow duplicate values | Ordered | Subset with [] |
---|---|---|---|---|---|
List | [1, 2, 3] |
No | Yes | Yes | Yes - index |
Dictionary | {key:value} |
No | Yes | Yes | Yes - key |
Set | {1, 2, 3} |
No | No | No | No |
Tuple | (1, 2, 3) |
Yes | Yes | Yes | Yes - index |
Introduction to Python for Developers