Python provides several built-in data structure types that allow developers to store and organize data in powerful ways. Mastering the proper use of lists, tuples, sets, and dictionaries is an essential skill for any Python programmer. These data structures each have their own strengths and use cases. This guide will provide practical exercises and examples for working with these data structures in real-world Python programs.
Table of Contents
Open Table of Contents
Introduction
Data structures provide ways of organizing and storing data so it can be accessed and manipulated efficiently. Python’s lists, tuples, sets, and dictionaries are known as the built-in sequence data types. Sequence data types allow indexing and slicing operations to access elements by their positions. Properly utilizing these data structures is key to managing program state and complexity as applications scale.
This guide will focus on hands-on examples and exercises to develop proficiency working with these core data structures. Readers will learn how to:
- Create and initialize lists, tuples, sets, and dictionaries
- Perform operations like indexing, slicing, adding, removing, and sorting elements
- Implement real-world data organization use cases using the strengths of each data structure
- Gain a deep understanding of these data structures by putting them into practice
Learning these foundational Python skills will build a solid basis for tackling more complex programming challenges and use cases. Let’s get started implementing them in example code!
Lists
Python lists are ordered, mutable sequences of arbitrary objects. Lists can be created using square brackets []
or the list()
constructor.
empty_list = []
languages = ["Python", "JavaScript", "C++"]
mixed_list = [1, "Hello", True]
list_from_range = list(range(5))
Lists are mutable, meaning the elements can be changed after creation.
languages[1] = "Java"
print(languages) # ["Python", "Java", "C++"]
Elements can be accessed via zero-based indexing. Negative indices access elements from the end of the list.
languages = ["Python", "JavaScript", "C++"]
print(languages[0]) # Python
print(languages[-1]) # C++
Slicing provides access to sub-lists using the syntax [start:stop:step]
. Omitting indices returns the full list.
languages = ["Python", "JavaScript", "C++", "Java"]
print(languages[1:3]) # ["JavaScript", "C++"]
print(languages[::2]) # ["Python", "C++"]
print(languages[:]) # ["Python", "JavaScript", "C++", "Java"]
Lists have many useful methods like append()
to add elements, insert()
to insert elements at an index, pop()
to remove elements by index, remove()
to remove by value, sort()
to sort in place, and more.
languages.append("Go") # Add element to end
languages.insert(1, "C#") # Insert at index 1
languages.sort()
print(languages) # ["C#", "C++", "Go", "Java", "JavaScript", "Python"]
languages.pop(2) # Remove element at index 2
print(languages) # ["C#", "C++", "Java", "JavaScript", "Python"]
languages.remove("Java") # Remove first instance of value "Java"
print(languages) # ["C#", "C++", "JavaScript", "Python"]
Loops like for
can iterate over lists:
for language in languages:
print(language)
Exercise 1: Find the Longest String in a List
Write a function to return the longest string from a list of strings.
def find_longest_string(strings):
longest = ""
for string in strings:
if len(string) > len(longest):
longest = string
return longest
print(find_longest_string(["PHP", "Python", "C++"])) # Python
This exercises core skills like iterating lists, comparing lengths, and updating variables conditionally.
Exercise 2: Filter List of Integers Greater than 5
Write a function that takes a list of integers and returns a new list containing only those greater than 5.
def filter_int_list(integers):
filtered = []
for num in integers:
if num > 5:
filtered.append(num)
return filtered
nums = [1, 6, 8, 3, 4]
print(filter_int_list(nums)) # [6, 8]
This provides practice using lists, loops, conditional logic, and creating new lists.
Exercise 3: Find Duplicates in a List
Write a function to find all duplicate values in a list.
def find_duplicates(values):
duplicates = []
seen = set()
for val in values:
if val in seen:
duplicates.append(val)
else:
seen.add(val)
return duplicates
values = [1, 2, 3, 2, 5, 3]
print(find_duplicates(values)) # [2, 3]
This brings in set data structures and introduces common techniques for finding duplicates.
These examples demonstrate practical real-world applications of Python lists. Mastering list usage unlocks the ability to model real data like sequences, stacks, and queues.
Tuples
Python tuples are ordered, immutable sequences of arbitrary objects. They are created using parentheses ()
or the tuple()
constructor.
empty_tuple = ()
languages = ("Python", "JavaScript", "C++")
mixed_tuple = (1, "Hello", True)
tuple_from_list = tuple(["foo", "bar"])
Tuples cannot be modified once created. Methods like append, insert, pop, remove, and sort are not available.
languages[0] = "Java" # Error! Tuples cannot be modified.
However, tuples support indexing, slicing, and unpacking like lists:
languages = ("Python", "JavaScript", "C++")
print(languages[1]) # JavaScript
print(languages[-1]) # C++
first, second = languages[0], languages[1]
print(first) # Python
print(second) # JavaScript
These properties make tuples useful for cases like composite keys in a dictionary, passing around fixed data, and ensuring values don’t change unintentionally.
Exercise 4: Unpack a Tuple into Individual Variables
Given a tuple, use tuple unpacking to assign each value to a separate variable.
details = ("John", 28, "New York")
name, age, city = details
print(name) # John
print(age) # 28
print(city) # New York
This is a common tuple operation to decompose a tuple into relevant variables.
Exercise 5: Swap Two Numbers Using a Tuple
Use a tuple to swap the values of two variables in Python.
a, b = 10, 20
print(a, b) # 10, 20
a, b = b, a
print(a, b) # 20, 10
Packing and unpacking provides an easy way to swap two values.
Tuples allow bundling related data together immutably, providing many possibilities for data organization and processing.
Sets
Python sets are unordered collections of unique, immutable objects. They can be created using braces {}
or the set()
constructor.
empty_set = set()
languages = {"Python", "C++", "JavaScript"}
mixed_set = {1, "Hello", True}
set_from_list = set([1, 2, 3, 2]) # {1, 2, 3}
Sets remove duplicates during creation.
nums = [1, 2, 1, 3, 4]
unique_nums = set(nums) # {1, 2, 3, 4}
Sets are unordered and cannot be indexed or sliced like lists and tuples.
Set objects support common mathematical operations like union, intersection, difference, and symmetric difference.
A = {1, 2, 3, 4}
B = {2, 4, 6, 8}
print(A | B) # Union - {1, 2, 3, 4, 6, 8}
print(A & B) # Intersection - {2, 4}
print(A - B) # Difference - {1, 3}
print(A ^ B) # Symmetric diff - {1, 3, 6, 8}
Other set methods include add()
to add an element, remove()
to remove by value, pop()
to remove an arbitrary element, clear()
to remove all elements, and more. Sets support loops to iterate over the unique elements.
Exercise 6: Find Unique Elements in Two Lists
Given two lists, find the unique elements in both using sets.
list1 = [1, 2, 3, 4]
list2 = [2, 4, 6, 8]
set1, set2 = set(list1), set(list2)
unique1 = set1 - set2
unique2 = set2 - set1
print(unique1) # {1, 3}
print(unique2) # {6, 8}
This provides experience using set operations to analyze differences between two sets.
Sets have many uses in Python, from removing duplicates to relational algebra operations. Mastering them provides a valuable addition to any developer’s data structure toolkit.
Dictionaries
Python dictionaries are mutable mappings of unique keys to values. They are created using braces {}
or the dict()
constructor.
empty_dict = {}
student = {"name": "John Doe", "age": 25, "courses": ["CS101", "MATH125"]}
dict_from_list = dict([('key1', 'value1'), ('key2', 'value2')])
Dictionaries are accessed via key rather than numeric index.
student = {"name": "John Doe", "age": 25}
print(student["name"]) # John Doe
print(student.get("age")) # 25
Keys must be immutable objects like string, numbers, or tuples. Values can be any arbitrary Python object.
Dictionaries support adding or modifying elements using key-value pairs:
student["email"] = "[email protected]" # Add new key-value
student["age"] = 26 # Modify existing value
print(student["age"]) # 26
The del
keyword removes a key-value pair. The .pop()
method does the same while also returning the value. The .popitem()
method removes an arbitrary key-value pair.
del student["email"]
age = student.pop("age") # Also returns value
print(age) # 26
student.popitem() # Remove random key-value pair
Dictionaries have a .keys()
method returning keys, .values()
returning values, and .items()
returning key-value tuples. These can be looped over.
for key in student.keys():
print(key)
for value in student.values():
print(value)
for key, value in student.items():
print(key, value)
Exercise 7: Count Word Frequency
Given a list of strings, return a dictionary with the strings as keys and frequency counts as the values.
def word_count(strings):
frequency = {}
for string in strings:
if string not in frequency:
frequency[string] = 1
else:
frequency[string] += 1
return frequency
print(word_count(["python", "python", "java", "C++"]))
# {"python": 2, "java": 1, "C++": 1}
This is useful counting pattern for dictionaries involving checking for existing keys and incrementing values.
Exercise 8: Invert a Dictionary
Invert the following dictionary mapping names to ages to instead map ages to names.
ages = {"Mike": 20, "Jen": 19, "Sally": 21}
inverted = {}
for name, age in ages.items():
if age not in inverted:
inverted[age] = [name]
else:
inverted[age].append(name)
print(inverted)
# {20: ["Mike"], 19: ["Jen"], 21: ["Sally"]}
Dictionaries combined with lists are powerful for grouping related data in ways like this example.
Dictionaries are incredibly useful for managing structured data, making them a key skill for Python programmers to know.
Conclusion
This guide covered practical examples and exercises for proficiently implementing Python’s essential list, tuple, set, and dictionary data structures. These built-in data structures provide versatile tools for efficiently organizing, accessing, and manipulating data in Python programs.
Some key takeaways:
- Lists are ordered, mutable sequences well-suited for stacking and queuing data
- Tuples are ordered, immutable sequences useful for fixed data like composite dictionary keys
- Sets are unordered collections of unique elements supporting efficient membership testing and mathematical operations
- Dictionaries map unique keys to values and excel at managing structured data
Continued practice with these data structures will enable tackling more complex Python programming problems. Readers should now feel confident implementing them in their own programs.
Mastering Python’s built-in data structures provides a strong foundation for leveling up your programming skills and becoming an adept Python developer. Combine this knowledge with Python’s functions, modules, and object orientation to build powerful and efficient applications.
Happy Python programming!