Python Data Structures

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will explore fundamental Python data structures: lists, tuples, sets, and dictionaries. Building upon your knowledge from previous labs, you will learn how to create, manipulate, and utilize these versatile data structures. This hands-on experience will deepen your understanding of Python's core concepts and prepare you for handling more complex data in your programs.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/DataStructuresGroup -.-> python/sets("`Sets`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") subgraph Lab Skills python/variables_data_types -.-> lab-393168{{"`Python Data Structures`"}} python/lists -.-> lab-393168{{"`Python Data Structures`"}} python/tuples -.-> lab-393168{{"`Python Data Structures`"}} python/dictionaries -.-> lab-393168{{"`Python Data Structures`"}} python/sets -.-> lab-393168{{"`Python Data Structures`"}} python/function_definition -.-> lab-393168{{"`Python Data Structures`"}} end

Working with Lists

In this step, you will learn about lists, which are ordered, mutable collections of items in Python.

  1. Open the Python interpreter by typing the following command in your terminal:

    python

    You should see the Python prompt (>>>), indicating that you're now in the Python interactive shell.

    Python Interpreter
  2. Let's start by creating a list. In the Python interpreter, type the following:

    >>> fruits = ["apple", "banana", "cherry"]
    >>> print(fruits)
    ['apple', 'banana', 'cherry']

    Lists in Python are created using square brackets [], with items separated by commas.

  3. You can access list elements using their index. Remember, Python uses zero-based indexing:

    >>> print(fruits[0])  ## First item
    apple
    >>> print(fruits[-1])  ## Last item
    cherry
  4. Lists are mutable, meaning you can change their contents:

    >>> fruits[1] = "blueberry"
    >>> print(fruits)
    ['apple', 'blueberry', 'cherry']
  5. You can add items to a list using the append() method or insert items at a specific position using the insert() method:

    >>> fruits.append("date")
    >>> print(fruits)
    ['apple', 'blueberry', 'cherry', 'date']
    >>> fruits.insert(1, "banana")
    >>> print(fruits)
    ['apple', 'banana', 'blueberry', 'cherry', 'date']
  6. To remove items, you can use the remove() method or the del statement:

    >>> fruits.remove("cherry")
    >>> print(fruits)
    ['apple', 'banana', 'blueberry', 'date']
    >>> del fruits[0]
    >>> print(fruits)
    ['banana', 'blueberry', 'date']
  7. Lists can contain items of different types, including other lists:

    >>> mixed_list = [1, "hello", 3.14, [1, 2, 3]]
    >>> print(mixed_list)
    [1, 'hello', 3.14, [1, 2, 3]]

Lists are versatile and widely used in Python for storing collections of items.

Understanding Tuples

In this step, you will learn about tuples, which are ordered, immutable sequences in Python.

  1. In the Python interpreter, let's create a tuple:

    >>> coordinates = (3, 4)
    >>> print(coordinates)
    (3, 4)

    Tuples are created using parentheses ().

  2. Like lists, you can access tuple elements using their index:

    >>> print(coordinates[0])
    3
    >>> print(coordinates[1])
    4
  3. However, unlike lists, tuples are immutable. This means you cannot change their contents after creation:

    >>> coordinates[0] = 5  ## This will raise an error
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'tuple' object does not support item assignment
  4. Tuples can contain items of different types:

    >>> person = ("Alice", 25, "Engineer")
    >>> name, age, occupation = person  ## Tuple unpacking
    >>> print(f"{name} is {age} years old and works as an {occupation}.")
    Alice is 25 years old and works as an Engineer.

    Tuple unpacking is a convenient way to assign multiple variables at once.

  5. You can create a tuple with a single element, but remember to include a comma:

    >>> single_item_tuple = (42,)
    >>> print(type(single_item_tuple))
    <class 'tuple'>

    Without the comma, Python will interpret it as a regular value in parentheses.

  6. Tuples are often used for returning multiple values from a function:

    >>> def get_dimensions():
    ...     return (1920, 1080)
    ...
    >>> width, height = get_dimensions()
    >>> print(f"Width: {width}, Height: {height}")
    Width: 1920, Height: 1080

Tuples are useful when you want to create a collection of items that shouldn't be modified.

Exploring Sets

In this step, you will learn about sets, which are unordered collections of unique elements in Python.

  1. Let's create a set in the Python interpreter:

    >>> fruits = {"apple", "banana", "cherry"}
    >>> print(fruits)
    {'cherry', 'banana', 'apple'}

    Sets are created using curly braces {} or the set() function. Note that the order of elements may vary when you print a set.

  2. Sets automatically remove duplicate elements:

    >>> numbers = {1, 2, 2, 3, 3, 4}
    >>> print(numbers)
    {1, 2, 3, 4}
  3. You can add elements to a set using the add() method:

    >>> fruits.add("date")
    >>> print(fruits)
    {'cherry', 'banana', 'apple', 'date'}
  4. To remove elements, use the remove() method:

    >>> fruits.remove("banana")
    >>> print(fruits)
    {'cherry', 'apple', 'date'}
  5. Sets support mathematical set operations like union, intersection, and difference:

    >>> set1 = {1, 2, 3}
    >>> set2 = {3, 4, 5}
    >>> print(set1.union(set2))  ## Union
    {1, 2, 3, 4, 5}
    >>> print(set1.intersection(set2))  ## Intersection
    {3}
    >>> print(set1.difference(set2))  ## Difference
    {1, 2}
  6. You can check if an element is in a set using the in keyword:

    >>> print("apple" in fruits)
    True
    >>> print("banana" in fruits)
    False

Sets are useful when you need to store unique elements or perform set operations.

Working with Dictionaries

In this step, you will learn about dictionaries, which are unordered collections of key-value pairs in Python.

  1. Let's create a dictionary in the Python interpreter:

    >>> person = {"name": "Alice", "age": 25, "occupation": "Engineer"}
    >>> print(person)
    {'name': 'Alice', 'age': 25, 'occupation': 'Engineer'}

    Dictionaries are created using curly braces {} with key-value pairs separated by colons :.

  2. You can access dictionary values using their keys:

    >>> print(person["name"])
    Alice
    >>> print(person["age"])
    25
  3. Dictionaries are mutable, so you can add or modify key-value pairs:

    >>> person["city"] = "New York"
    >>> person["age"] = 26
    >>> print(person)
    {'name': 'Alice', 'age': 26, 'occupation': 'Engineer', 'city': 'New York'}
  4. To remove a key-value pair, use the del statement:

    >>> del person["city"]
    >>> print(person)
    {'name': 'Alice', 'age': 26, 'occupation': 'Engineer'}
  5. You can check if a key exists in a dictionary using the in keyword:

    >>> print("name" in person)
    True
    >>> print("city" in person)
    False
  6. Dictionaries have useful methods like keys(), values(), and items():

    >>> print(person.keys())
    dict_keys(['name', 'age', 'occupation'])
    >>> print(person.values())
    dict_values(['Alice', 26, 'Engineer'])
    >>> print(person.items())
    dict_items([('name', 'Alice'), ('age', 26), ('occupation', 'Engineer')])
  7. You can use dictionary comprehension to create dictionaries concisely:

    >>> squares = {x: x**2 for x in range(5)}
    >>> print(squares)
    {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Dictionaries are extremely useful for storing and retrieving data with unique keys.

Putting It All Together

In this final step, you will create a program that utilizes all the data structures you've learned in this lab.

  1. Exit the Python interpreter by typing exit() or pressing Ctrl+D.

  2. Open the WebIDE in the LabEx VM environment.

    WebIDE
  3. Create a new file named contact_manager.py in the ~/project directory:

    touch ~/project/contact_manager.py
  4. Open the newly created file in the WebIDE editor and add the following content:

    def add_contact(contacts, name, phone, email):
        contacts[name] = {"phone": phone, "email": email}
        print(f"Contact {name} added successfully.")
    
    def remove_contact(contacts, name):
        if name in contacts:
            del contacts[name]
            print(f"Contact {name} removed successfully.")
        else:
            print(f"Contact {name} not found.")
    
    def display_contacts(contacts):
        if contacts:
            print("\nContact List:")
            for name, info in contacts.items():
                print(f"Name: {name}, Phone: {info['phone']}, Email: {info['email']}")
        else:
            print("Contact list is empty.")
    
    def main():
        contacts = {}
        favorite_contacts = set()
    
        while True:
            print("\nContact Manager")
            print("1. Add Contact")
            print("2. Remove Contact")
            print("3. Display Contacts")
            print("4. Add to Favorites")
            print("5. Display Favorites")
            print("6. Exit")
    
            choice = input("Enter your choice (1-6): ")
    
            if choice == "1":
                name = input("Enter name: ")
                phone = input("Enter phone number: ")
                email = input("Enter email: ")
                add_contact(contacts, name, phone, email)
            elif choice == "2":
                name = input("Enter name to remove: ")
                remove_contact(contacts, name)
            elif choice == "3":
                display_contacts(contacts)
            elif choice == "4":
                name = input("Enter name to add to favorites: ")
                if name in contacts:
                    favorite_contacts.add(name)
                    print(f"{name} added to favorites.")
                else:
                    print(f"Contact {name} not found.")
            elif choice == "5":
                print("\nFavorite Contacts:")
                for name in favorite_contacts:
                    print(name)
            elif choice == "6":
                print("Thank you for using Contact Manager. Goodbye!")
                break
            else:
                print("Invalid choice. Please try again.")
    
    if __name__ == "__main__":
        main()

    This program demonstrates the use of dictionaries, sets, and lists to create a simple contact management system.

  5. Save the file (auto-save is enabled in WebIDE) and run it using the following command in the terminal:

    python ~/project/contact_manager.py
  6. Interact with the program by adding contacts, removing contacts, displaying the contact list, adding contacts to favorites, and displaying favorite contacts. Here's an example interaction:

    Contact Manager
    1. Add Contact
    2. Remove Contact
    3. Display Contacts
    4. Add to Favorites
    5. Display Favorites
    6. Exit
    Enter your choice (1-6): 1
    Enter name: Alice
    Enter phone number: 123-456-7890
    Enter email: [email protected]
    Contact Alice added successfully.
    
    Contact Manager
    1. Add Contact
    2. Remove Contact
    3. Display Contacts
    4. Add to Favorites
    5. Display Favorites
    6. Exit
    Enter your choice (1-6): 1
    Enter name: Bob
    Enter phone number: 987-654-3210
    Enter email: [email protected]
    Contact Bob added successfully.
    
    Contact Manager
    1. Add Contact
    2. Remove Contact
    3. Display Contacts
    4. Add to Favorites
    5. Display Favorites
    6. Exit
    Enter your choice (1-6): 3
    
    Contact List:
    Name: Alice, Phone: 123-456-7890, Email: [email protected]
    Name: Bob, Phone: 987-654-3210, Email: [email protected]
    
    Contact Manager
    1. Add Contact
    2. Remove Contact
    3. Display Contacts
    4. Add to Favorites
    5. Display Favorites
    6. Exit
    Enter your choice (1-6): 4
    Enter name to add to favorites: Alice
    Alice added to favorites.
    
    Contact Manager
    1. Add Contact
    2. Remove Contact
    3. Display Contacts
    4. Add to Favorites
    5. Display Favorites
    6. Exit
    Enter your choice (1-6): 5
    
    Favorite Contacts:
    Alice
    
    Contact Manager
    1. Add Contact
    2. Remove Contact
    3. Display Contacts
    4. Add to Favorites
    5. Display Favorites
    6. Exit
    Enter your choice (1-6): 6
    Thank you for using Contact Manager. Goodbye!

This program demonstrates the practical use of dictionaries (for storing contact information), sets (for storing favorite contacts), and lists (implicitly used in the menu system).

Summary

In this lab, you have explored fundamental Python data structures: lists, tuples, sets, and dictionaries. You have learned how to create, manipulate, and utilize these versatile data structures, which are essential for efficient data management in Python programming.

You started by working with lists, learning how to create, access, and modify ordered collections of items. You then explored tuples, understanding their immutability and their use cases for representing fixed collections of elements. Next, you delved into sets, discovering their ability to store unique elements and perform mathematical set operations. Finally, you worked with dictionaries, learning how to manage key-value pairs for efficient data lookup and storage.

To reinforce these concepts, you created a practical contact management program that utilized multiple data structures. This program demonstrated how different data structures can work together in a real-world application, showcasing the power and flexibility of Python's data structures.

These data structures form the backbone of many Python programs, allowing you to organize and manipulate data efficiently. As you continue your Python journey, you'll find these structures invaluable for solving a wide range of programming problems. Remember to practice using these data structures in various scenarios to reinforce your understanding and become more proficient in Python programming.

Other Python Tutorials you may like