Introduction to Data Structures
Data structures are used to store and organize data in a program. Python has built-in data structures, such as lists, tuples, sets, and dictionaries.
Lists
A list is an ordered, mutable collection of elements. You can create a list using square brackets '[]' and access elements using indices.
Example:
my_list = [1, 2, 3, 4, 5]
print(my_list[0]) # Output: 1
Tuples
A tuple is an ordered, immutable collection of elements. You can create a tuple using parentheses '()' and access elements using indices.
Example:
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[0]) # Output: 1
Sets
A set is an unordered, mutable collection of unique elements. You can create a set using the 'set()' function or curly braces '{}'.
Example:
my_set = {1, 2, 3, 4, 5}
print(len(my_set)) # Output: 5
Dictionaries
A dictionary is an unordered, mutable collection of key-value pairs. You can create a dictionary using curly braces '{}' and access elements using keys.
Example:
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict['a']) # Output: 1
Hands-on Exercises
- Write a Python script that creates a list of numbers and finds the sum of all the even numbers in the list.
- Create a Python script that uses a dictionary to store and print student names and their corresponding grades.
- Write a Python script that takes a list of words and returns a dictionary with the words as keys and their frequencies as values.
Real-World Example
Suppose you are building an inventory management system for a store. You can use Python’s data structures, such as dictionaries and lists, to store product information (name, price, quantity) and manage the inventory efficiently.
Additional Resources
- Python documentation: https://docs.python.org/3/tutorial/datastructures.html
- Real Python: https://realpython.com/python-data-structures/
- W3Schools Python tutorial: https://www.w3schools.com/python/python_lists.asp
Summary and Next Steps
In this lesson, you have learned about:
- Basic data structures in Python
- Lists and their properties
- Tuples and their properties
- Sets and their properties
- Dictionaries and their properties
In the next lesson, you will learn about object-oriented programming in Python, including classes, objects, inheritance, and polymorphism. This knowledge will help you create more structured and modular programs.
Remember to review the material periodically and practice your skills to reinforce your learning. Good luck on your journey to becoming a Python developer!
Review Questions
- What are the differences between lists and tuples in Python?
- Explain how sets ensure that all elements are unique.
- Describe the key-value structure of dictionaries in Python.
- Write a Python script that removes duplicates from a list by converting it to a set and then back to a list.
- Create a Python script that uses a dictionary to store and manipulate a phonebook (add, delete, and search for contacts).



