Module 7 - Lists and Data Structures Header

Module 7 - Lists and Data Structures

Introduction

In this module, we'll cover four essential data structures: lists, dictionaries, sets, and tuples. These structures serve different purposes and can greatly enhance your ability to organize and manipulate data.

Let's start with lists, which allow you to store multiple values in a single variable. With lists, you can easily add, remove, or modify elements. They are perfect for storing collections of related items, like names or numbers. On the other hand, dictionaries excel at associating values with specific keys, making them ideal for tasks like mapping data or organizing configurations. They provide fast lookup times and enable efficient key-based operations.

Next up, we have sets, which are useful when dealing with unique elements or performing mathematical set operations. Sets automatically remove duplicates, making them great for eliminating repetition or finding common elements. Lastly, tuples offer an immutable and ordered collection of values. They are valuable when you need data integrity and want to ensure that elements remain unchanged.

Understanding these data structures will unlock a range of possibilities in your programming journey. Whether you're building applications, analyzing data, or solving complex problems, having a grasp of lists, dictionaries, sets, and tuples will prove invaluable. So, let's dive in and discover the strengths, weaknesses, and use cases of each structure to enhance your Python skills!



Lists

Lists are one of the most versatile and commonly used data structures in Python. They are ordered, mutable (changeable), and can hold any type of object. You can think of a list as a collection of elements enclosed in square brackets [], with each element separated by a comma.

Example:

fruits = ['apple', 'banana', 'orange']

Strengths:

  • Lists allow you to store and manipulate multiple values in a single variable.
  • They support indexing and slicing, making it easy to access and modify elements.
  • Lists can be modified by adding, removing, or modifying elements, which is useful when you need to update the data.

Limitations:

  • Lists can be slower for large datasets compared to other data structures like sets or dictionaries.
  • Searching for an element in a list can take longer if the list is unsorted.

Use Cases:

  • Storing a collection of related items, such as a list of students' names or a list of numbers for calculations.
  • Iterating over a sequence of elements using loops or list comprehensions.
  • Implementing stacks or queues.


Dictionaries

Dictionaries, also known as associative arrays or hash maps, are unordered collections of key-value pairs. They are enclosed in curly braces {} and use a colon : to separate keys and values. Dictionaries are mutable, meaning you can modify them after creation.

Example:

student = {'name': 'Alice', 'age': 20, 'major': 'Computer Science'}

Strengths:

  • Dictionaries provide fast lookup times by using keys as unique identifiers.
  • They are ideal for scenarios where you want to associate values with specific keys or perform key-based operations efficiently.
  • Dictionaries can store heterogeneous data types as values.

Limitations:

  • Dictionaries don't maintain any particular order, so the order of elements may not be preserved.
  • They require unique keys, and duplicate keys will overwrite existing values.

Use Cases:

  • Storing and retrieving data based on a key, such as a database record or configuration settings.
  • Mapping values between different representations.
  • Counting occurrences of items using keys as unique identifiers.
     


Sets

Sets are unordered collections of unique elements. They are defined by enclosing comma-separated elements in curly braces {} or by using the set() function. Sets don't allow duplicate values, and they automatically remove duplicates if present.

Example:

fruits = {'apple', 'banana', 'orange'}

Strengths:

  • Sets excel at performing mathematical set operations like union, intersection, and difference.
  • They efficiently eliminate duplicate values from a sequence.
  • Sets provide membership testing, which allows you to quickly check if an element exists in the set.

Limitations:

  • Sets don't maintain order, so you can't access elements by their index.
  • Since sets only contain unique elements, they may not be suitable for scenarios where you need to preserve duplicates.

Use Cases:

  • Removing duplicates from a list or any other sequence.
  • Checking for common elements between two collections.
  • Performing mathematical operations like finding the union or intersection of sets.
     


Tuples

Tuples are ordered, immutable collections of elements enclosed in parentheses (). They are similar to lists but cannot be modified once created.

Example:

point = (3, 5)
person = ("Alice", 25, "Engineer")

Limitations:

  • Tuples are immutable, meaning you cannot modify elements after creation.

Strengths:

  • Tuples provide a lightweight way to store and pass around a collection of related values.
  • They can be used as dictionary keys, unlike lists.

Weaknesses:

  • Lack of mutability limits dynamic changes to the tuple's elements.
  • Tuples do not offer extensive built-in methods like lists.

Use Cases:

  • Storing a fixed sequence of values that should not be modified.
  • Returning multiple values from a function or method.


List Indexes

In Python, indexes refer to the positions of elements within a list. Each element in a list has a unique index that represents its location. Indexing in lists is zero-based, meaning the first element has an index of 0, the second element has an index of 1, and so on.

You can use indexes to access and retrieve specific elements from a list, modify elements, or perform various operations. Here's an explanation of how indexes work in lists, along with examples:

Accessing Elements by Index:

To access a specific element in a list, you can use square brackets [] with the desired index value. This allows you to retrieve the element at that particular position.

Example:

fruits = ["apple", "banana", "orange"]
print(fruits[0]) # Output: "apple"
print(fruits[2]) # Output: “orange”

In this example, the element at index 0 is accessed using fruits[0], which returns the value "apple". Similarly, fruits[2] retrieves the element at index 2, giving the value "orange".

Modifying Elements by Index:

Since lists are mutable, you can modify elements by assigning new values to specific indexes.

Example:

numbers = [1, 2, 3, 4, 5]
numbers[2] = 10
print(numbers) # Output: [1, 2, 10, 4, 5]

In this example, the element at index 2 in the numbers list is modified from 3 to 10 using assignment. By specifying the index and providing a new value, you can update the list accordingly.

Negative Indexing:

In addition to positive indexes, Python allows negative indexing, where the index value starts from the end of the list. The last element has an index of -1, the second-to-last element has an index of -2, and so on.

Example:

fruits = ["apple", "banana", "orange"]
print(fruits[-1]) # Output: "orange"
print(fruits[-2]) # Output: “banana”

In this example, negative indexes are used to access elements from the end of the list. fruits[-1] retrieves the last element, "orange", while fruits[-2] retrieves the second-to-last element, "banana".

Out-of-Range Indexes:

When working with indexes, it's crucial to ensure they fall within the valid range of the list. Accessing an index that is outside the range of the list will result in an IndexError.

Example:

numbers = [1, 2, 3]
print(numbers[3]) # Raises IndexError: list index out of range

In this example, the index 3 is out of range for the numbers list, resulting in an IndexError.

Understanding indexes allows you to access, modify, and manipulate specific elements within a list. It is an essential concept for working effectively with lists in Python.



Adding Items: List

In Python, the append() function is used to add new items or elements to the end of a list. It allows you to dynamically expand a list by appending elements without explicitly specifying the index position. Here's how to use the append() function in Python, along with examples:

Syntax:

list_name.append(item)
  • list_name: The name of the list to which the item will be appended.
  • item: The element or item to be added to the list.

Example 1: Adding a Single Item to a List:

fruits = ["apple", "banana", "orange"]
fruits.append("grape")
print(fruits) # Output: ["apple", "banana", "orange", "grape"]

In this example, the append() function is used to add the item "grape" to the fruits list. The element is added to the end of the list, extending the list by one element.

Example 2: Adding Multiple Items to a List using a Loop:

numbers = [1, 2, 3, 4, 5]
new_numbers = [6, 7, 8]

for num in new_numbers:
numbers.append(num)

print(numbers) # Output: [1, 2, 3, 4, 5, 6, 7, 8]

In this example, the append() function is used within a loop to add multiple items from the new_numbers list to the numbers list. Each element in new_numbers is iterated over, and append() adds it to the end of the numbers list.

Note: It's important to remember that when using append(), the item provided as an argument is added as a single element, even if it is itself a list or any other iterable. If you want to add the individual elements of another iterable to a list, you may need to use techniques like list concatenation or the extend() method.

Example 3: Adding Elements to an Empty List:

my_list = []
my_list.append(10)
my_list.append(20)
my_list.append(30)
print(my_list) # Output: [10, 20, 30]

In this example, an empty list my_list is created, and the append() function is used to add elements to it. Each call to append() adds a new item to the end of the list.

The append() function is a convenient way to add elements to the end of a list dynamically. It allows you to expand and modify lists by appending items without explicitly specifying the index position.



Adding Items: Dictionary

In Python, you can add items to a dictionary by assigning a value to a new or existing key. Dictionaries are mutable data structures that store key-value pairs, and adding items involves specifying the key and assigning a value to it. Here's how to add items to a dictionary in Python, along with examples:

Example 1: Adding a Single Item to a Dictionary:

fruits = {"apple": 5, "banana": 3}
fruits["orange"] = 2
print(fruits) # Output: {"apple": 5, "banana": 3, "orange": 2}

In this example, a dictionary named fruits is initially defined with two key-value pairs. To add a new item, the key "orange" is used, and its corresponding value 2 is assigned to it. The new key-value pair is added to the dictionary.

Example 2: Adding Multiple Items to a Dictionary:

fruits = {"apple": 5, "banana": 3}
new_fruits = {"orange": 2, "grape": 4}
fruits.update(new_fruits)
print(fruits) # Output: {"apple": 5, "banana": 3, "orange": 2, "grape": 4}

In this example, the update() method is used to add multiple items from the new_fruits dictionary to the fruits dictionary. The update() method merges the key-value pairs from new_fruits into fruits, adding any new items and updating existing ones.

Adding items to a dictionary is a fundamental operation in Python. By assigning a value to a new or existing key, you can dynamically expand or modify the dictionary, making it a powerful data structure for storing and organizing data.



Modifying Items

Here's how to modify elements in both lists and dictionaries using Python, along with examples for each.

Modifying Elements in a List:

Lists in Python are mutable, meaning you can change or modify their elements after creation. To modify an element in a list, you can directly access it using its index and assign a new value to it. Here's an example:

fruits = ["apple", "banana", "orange"]
fruits[1] = "grape"
print(fruits) # Output: ["apple", "grape", "orange"]

In this example, the element at index 1 in the fruits list, which is initially "banana", is modified to "grape" using assignment. By assigning a new value to the specific index, the list is updated accordingly.

Modifying Elements in a Dictionary:

Dictionaries in Python store key-value pairs, and to modify the value of a specific key in a dictionary, you can assign a new value to that key. Here's an example:

fruits = {"apple": 5, "banana": 3, "orange": 2}
fruits["banana"] = 7
print(fruits) # Output: {"apple": 5, "banana": 7, "orange": 2}

In this example, the value associated with the key "banana" in the fruits dictionary is modified. By assigning a new value of 7 to the key "banana", the value is updated in the dictionary.

Note: If the specified key already exists in the dictionary, the assigned value will replace the existing value associated with that key. If the key is not found in the dictionary, a new key-value pair will be created.

Both lists and dictionaries offer the flexibility to modify their elements, allowing you to update and manipulate data as needed within your programs.



Removing Items: List

In Python, there are several methods and techniques to remove items from a list. Here are the common approaches:

Using the remove() method:

The remove() method removes the first occurrence of a specified value from the list.

Example:

fruits = ["apple", "banana", "orange"]
fruits.remove("banana")
print(fruits) # Output: ["apple", "orange"]

Using the pop() method:

The pop() method removes and returns the item at a specific index from the list.

Example:

fruits = ["apple", "banana", "orange"]
removed_fruit = fruits.pop(1)
print(removed_fruit) # Output: "banana"
print(fruits) # Output: ["apple", "orange"]

Using the del statement:

The del statement can remove an item from a list using its index or remove a slice of items.

Example:

fruits = ["apple", "banana", "orange"]
del fruits[1]
print(fruits) # Output: ["apple", "orange"]

Using list comprehension or filter:

List comprehension or the filter() function can be used to create a new list without specific elements based on a condition.

Example:

fruits = ["apple", "banana", "orange"]
new_fruits = [fruit for fruit in fruits if fruit != "banana"]
print(new_fruits) # Output: ["apple", "orange"]


Removing Items: Dictionary

In Python, there are also various methods and techniques to remove items from a dictionary. Here are the common approaches:

Using the del statement:

The del statement can remove a key-value pair from a dictionary using the specified key.

Example:

fruits = {"apple": 5, "banana": 3, "orange": 2}
del fruits["banana"]
print(fruits) # Output: {"apple": 5, "orange": 2}

Using the pop() method:

The pop() method removes and returns the value associated with a specific key from the dictionary.

Example:

fruits = {"apple": 5, "banana": 3, "orange": 2}
removed_value = fruits.pop("banana")
print(removed_value) # Output: 3
print(fruits) # Output: {"apple": 5, "orange": 2}

Using dictionary comprehension:

Dictionary comprehension can be used to create a new dictionary without specific key-value pairs based on a condition.

Example:

fruits = {"apple": 5, "banana": 3, "orange": 2}
new_fruits = {key: value for key, value in fruits.items() if key != "banana"}
print(new_fruits) # Output: {"apple": 5, "orange": 2}


Useful List Methods

Below you will find some important-to-know list methods, which will allow you to manipulate and do useful things with lists.

index()

Returns the index of the first occurrence of a specified element in a list. Raises a ValueError if the element is not found.

fruits = ["apple", "banana", "orange"]
index = fruits.index("banana")
print(index) # Output: 1

count()

Returns the number of occurrences of a specified element in a list.

fruits = ["apple", "banana", "orange", "banana"]
count = fruits.count("banana")
print(count) # Output: 2

sort()

Sorts the elements of a list in ascending order. The original list is modified in-place.

numbers = [3, 1, 4, 2]
numbers.sort()
print(numbers) # Output: [1, 2, 3, 4]

reverse()

Reverses the order of elements in a list. The original list is modified in-place.

fruits = ["apple", "banana", "orange"]
fruits.reverse()
print(fruits) # Output: ["orange", "banana", "apple"]

copy()

Returns a shallow copy of the list. The new list references the same elements as the original list.

fruits = ["apple", "banana", "orange"]
fruits_copy = fruits.copy()
print(fruits_copy) # Output: ["apple", "banana", "orange"]

len()

Returns the number of elements in a list.

fruits = ["apple", "banana", "orange"]
length = len(fruits)
print(length) # Output: 3

clear()

Removes all elements from a list, making it empty.

fruits = ["apple", "banana", "orange"]
fruits.clear()
print(fruits) # Output: []

min()

Returns the minimum value from a list. Works with lists of numbers or strings based on their natural order.

numbers = [3, 1, 4, 2]
minimum = min(numbers)
print(minimum) # Output: 1

max()

Returns the maximum value from a list. Works with lists of numbers or strings based on their natural order.

numbers = [3, 1, 4, 2]
maximum = max(numbers)
print(maximum) # Output: 4


Useful Dictionary Methods

Here are some of the most common/useful dictionary methods, including examples of how to use them:

keys()

Returns a view object that contains the keys of the dictionary.

fruits = {"apple": 5, "banana": 3, "orange": 2}
keys = fruits.keys()
print(keys) # Output: dict_keys(["apple", "banana", "orange"])

values()

Returns a view object that contains the values of the dictionary.

fruits = {"apple": 5, "banana": 3, "orange": 2}
values = fruits.values()
print(values) # Output: dict_values([5, 3, 2])

items()

Returns a view object that contains key-value pairs as tuples.

fruits = {"apple": 5, "banana": 3, "orange": 2}
items = fruits.items()
print(items) # Output: dict_items([("apple", 5), ("banana", 3), ("orange", 2)])

get()

Returns the value associated with a specified key. Allows specifying a default value if the key is not found.

fruits = {"apple": 5, "banana": 3, "orange": 2}
value = fruits.get("banana")
print(value) # Output: 3
value = fruits.get("mango", 0) # Default value if key is not found
print(value) # Output: 0

update()

Updates the dictionary with the key-value pairs from another dictionary or an iterable of key-value pairs.

fruits = {"apple": 5, "banana": 3}
new_fruits = {"orange": 2, "mango": 4}
fruits.update(new_fruits)
print(fruits) # Output: {"apple": 5, "banana": 3, "orange": 2, "mango": 4}

clear()

Removes all key-value pairs from the dictionary, making it empty.

fruits = {"apple": 5, "banana": 3, "orange": 2}
fruits.clear()
print(fruits) # Output: {}

copy()

Returns a shallow copy of the dictionary. The new dictionary references the same key-value pairs as the original dictionary.

fruits = {"apple": 5, "banana": 3, "orange": 2}
fruits_copy = fruits.copy()
print(fruits_copy) # Output: {"apple": 5, "banana": 3, "orange": 2}

len()

Returns the number of key-value pairs in the dictionary.

fruits = {"apple": 5, "banana": 3, "orange": 2}
length = len(fruits)
print(length) # Output: 3

in keyword

Checks if a specified key exists in the dictionary.

fruits = {"apple": 5, "banana": 3, "orange": 2}
if "banana" in fruits:
print("Banana is present!")

fromkeys()

Creates a new dictionary with specified keys and a default value.

keys = ["apple", "banana", "orange"]
default_value = 0
fruits = dict.fromkeys(keys, default_value)
print(fruits) # Output: {"apple": 0, "banana": 0, "orange": 0}

Videos for Module 7 - Lists and Data Structures

7-1: Introducing Lists and Dictionaries (1:22)

7-2: Introducing Lists in Python (3:51)

7-3: Introducing Dictionaries in Python (4:28)

7-4: Accessing Data in Lists & Dictionaries (6:50)

7-5: Changing Values in Lists & Dictionaries (5:22)

7-6: Removing Values from Lists & Dictionaries (5:45)

7-7: Reviewing List Methods (8:50)

7-8: S7 Explanation (5:29)

7-9: Advanced Calculator Review Walkthrough (23:31)

7-10: Introducing Tuples (8:47)

7-11: Nested Lists in Python (8:13)

7-12: Nested Dictionaries (4:45)

7-13: A7 Example Code Walkthrough and Explanation (29:01)

Key Terms for Module 7 - Lists and Data Structures

No terms have been published for this module.

Quiz Yourself - Module 7 - Lists and Data Structures

Test your knowledge of this module by choosing options below. You can keep trying until you get the right answer.

Skip to the Next Question