Python (Beginner) - Lesson 6: Data Structures – Lists, Tuples, Dictionaries, and Sets

Welcome to Lesson 6! In this lesson, we will dive into the essential data structures in Python: lists, tuples, dictionaries, and sets. These data structures are the building blocks for managing and organizing data in your programs. By mastering them, you will be able to store, manipulate, and retrieve information efficiently. Throughout this lesson, we will use Visual Studio Code as our development environment to write, run, and debug our Python code. Make sure you have VS Code open with the Python extension installed so you can follow along seamlessly.

Definitions & Explanations

Lists:

  • Definition:
    A list is an ordered, mutable collection of items. This means that the items in a list maintain a specific order, and you can modify the list after its creation by adding, removing, or changing its elements.

  • Key Characteristics:

    • Ordered: The items in the list maintain the order in which they are added.

    • Mutable: You can change the list's contents, making it very flexible for various operations.

    • Heterogeneous: Lists can contain items of different data types, such as integers, strings, and even other lists.

  • Common Methods:

    • append(): Adds an element to the end of the list.

    • insert(): Inserts an element at a specified index.

    • remove(): Removes the first occurrence of a specified value.

    • pop(): Removes and returns an element at a given index (or the last element if no index is provided).

    • sort(): Sorts the list in ascending or descending order.

    • reverse(): Reverses the elements of the list.

  • Usage Scenario:
    Use lists when you need to maintain an ordered collection that you may want to modify dynamically during program execution.

Tuples:

  • Definition:
    A tuple is an ordered, immutable collection of items. Unlike lists, once a tuple is created, you cannot change its contents.

  • Key Characteristics:

    • Ordered: The elements in a tuple have a fixed order.

    • Immutable: Once defined, the contents cannot be altered, which can help prevent accidental changes.

    • Heterogeneous: Tuples, like lists, can contain elements of different data types.

  • Usage Scenario:
    Use tuples for data that should remain constant throughout the execution of your program, such as coordinates, RGB color values, or configuration settings.

Dictionaries:

  • Definition:
    A dictionary is an unordered (though in Python 3.7+ insertion order is preserved), mutable collection of key-value pairs. Each key in a dictionary is unique and is used to retrieve its corresponding value.

  • Key Characteristics:

    • Key-Value Pairs: Each item in a dictionary is stored as a pair consisting of a key and a value.

    • Mutable: You can add, update, or remove key-value pairs.

    • Efficient Lookup: Dictionaries are optimized for retrieving values when you know the key.

  • Common Methods:

    • keys(): Returns a view of all keys in the dictionary.

    • values(): Returns a view of all values.

    • items(): Returns a view of all key-value pairs.

    • get(): Retrieves a value for a given key, with an option to return a default if the key is not found.

  • Usage Scenario:
    Use dictionaries when you need to associate pieces of data, such as a student's name with their age or a product code with its price.

Sets:

  • Definition:
    A set is an unordered collection of unique items. Sets are useful for operations that involve membership testing, removing duplicates, and mathematical operations like unions and intersections.

  • Key Characteristics:

    • Unordered: There is no guaranteed order of elements in a set.

    • Unique Elements: Sets automatically discard duplicate items.

    • Mutable (but elements must be immutable): You can add or remove items, but the individual items stored in a set must be immutable (e.g., numbers, strings, tuples).

  • Common Methods:

    • add(): Adds an element to the set.

    • remove(): Removes a specified element.

    • union(): Returns a set containing all items from both sets.

    • intersection(): Returns a set with items common to both sets.

  • Usage Scenario:
    Use sets when you need to ensure that your collection contains no duplicate elements or when you need to perform fast membership tests.

Example Code

Below are detailed code examples that illustrate how to create and manipulate each of these data structures. Open Visual Studio Code, create a new Python file (for instance, lesson6_data_structures.py), and enter the following code.

# List Example: Creating and modifying a list of fruits
fruits = ["apple", "banana", "cherry"]
fruits.append("date")  # Append "date" to the list
print("List of fruits:", fruits)  # Expected output: ['apple', 'banana', 'cherry', 'date']

# Tuple Example: Defining a tuple for screen dimensions
dimensions = (1920, 1080)
print("Screen dimensions:", dimensions)  # Expected output: (1920, 1080)

# Dictionary Example: Storing student information as key-value pairs
student = {"name": "Alice", "age": 22, "major": "Computer Science"}
print("Student Info:", student)
# Accessing a specific value:
print("Student's major:", student["major"])  # Expected output: Computer Science

# Set Example: Creating a set to demonstrate uniqueness
unique_numbers = {1, 2, 3, 2, 1}  # Duplicates will be removed automatically
print("Unique numbers:", unique_numbers)  # Expected output: {1, 2, 3}

Explanation:

  • Lists:
    The code creates a list named fruits with three initial elements. The append() method is then used to add "date" to the list. The updated list is printed, showing that lists maintain insertion order and can be modified.

  • Tuples:
    A tuple named dimensions is created to store screen dimensions. Since tuples are immutable, you cannot change these values once set. The tuple is printed to confirm its contents.

  • Dictionaries:
    A dictionary named student is defined with keys such as "name", "age", and "major". The dictionary is printed in full, and then a specific value is accessed using its key (student["major"]).

  • Sets:
    A set named unique_numbers is created with some repeated values. The print statement shows that the duplicates have been automatically removed, leaving only unique elements in the set.

Tasks

Now it’s time for you to apply these concepts in practice. Complete the following tasks using Visual Studio Code:

  1. Favorite Movies List and Dictionary:

    • Create a new Python file (e.g., movies.py).

    • Write a program that:

      • Creates a list of your favorite movies.

      • Creates a dictionary where the keys are the movie titles and the values are their release years.

    • Print both the list and the dictionary to the terminal.

    • Use comments in your code to explain what each part does.

  2. Eliminating Duplicates with Sets:

    • Create a new Python file (e.g., remove_duplicates.py).

    • Write a program that:

      • Creates a list of movie titles, intentionally including duplicate entries.

      • Converts the list into a set to automatically remove duplicates.

      • Prints both the original list and the resulting set to compare the outputs.

    • Experiment with modifying the list and observe how the set changes.

  3. Advanced List Manipulation:

    • Create a new Python file (e.g., list_manipulation.py).

    • Write a program that:

      • Defines a list of numbers.

      • Performs the following operations in sequence:

        • Append a new number to the list.

        • Remove a specific number from the list.

        • Sort the list in ascending order.

        • Reverse the list.

      • After each operation, print the list to observe the changes.

    • Comment each section of your code to describe what is happening.

Recall Questions

To reinforce your understanding, review and answer the following questions:

  • What is the main difference between a list and a tuple?

    • Consider aspects such as mutability and use cases in your explanation.

  • How do you access a value in a dictionary?

    • Describe the process of using a key to retrieve its associated value.

  • In what scenarios is a set more useful than a list?

    • Discuss how sets help with eliminating duplicate values and performing efficient membership tests.

By the end of Lesson 6, you should be comfortable working with Python’s core data structures. These skills will allow you to manage and manipulate data effectively in your programs. Continue practicing by writing and experimenting with your own code in Visual Studio Code. As you explore more complex projects, these data structures will be indispensable tools in your Python toolkit.

Previous
Previous

Python (Beginner) - Lesson 5: Functions and Modular Programming

Next
Next

Python (Beginner) - Lesson 7: Working with Libraries and Modules