Module 6 of 15 · Python for AI — Complete Beginner Course · Beginner

Data Structures

Duration: 5 min

This module delves into the fundamental data structures in Python: lists, tuples, dictionaries, and sets. Understanding these structures is crucial as they form the backbone of efficient data manipulation and storage in Python, enabling developers to build complex applications with ease.

Lists

Lists are ordered, mutable collections that can hold a variety of data types. They are versatile and widely used for storing collections of items. Lists are defined by enclosing elements in square brackets, separated by commas. They support operations like indexing, slicing, and methods for adding, removing, and sorting elements.

my_list = [1, 2, 3, 'a', 'b', 'c']
# Accessing an element
print(my_list[0])  # Output: 1

# Adding an element
my_list.append('d')
print(my_list)  # Output: [1, 2, 3, 'a', 'b', 'c', 'd']

# Removing an element
my_list.remove('a')
print(my_list)  # Output: [1, 2, 3, 'b', 'c', 'd']

Try it in Google Colab: Open in Colab

1
[1, 2, 3, 'b', 'c', 'd', 'd']
[1, 2, 3, 'b', 'c', 'd']

Tuples

Tuples are similar to lists but are immutable, meaning their elements cannot be changed after creation. They are defined by enclosing elements in parentheses. Tuples are often used for fixed collections of items, such as coordinates or database records, and can be used as keys in dictionaries.

Learn more: https://docs.python.org/3/tutorial/

my_tuple = (1, 2, 3, 'a', 'b', 'c')
# Accessing an element
print(my_tuple[0])  # Output: 1

# Attempting to modify an element will raise an error
# my_tuple[0] = 4  # This will raise a TypeError

# Unpacking a tuple
a, b, c, *rest = my_tuple
print(a, b, c)  # Output: 1 2 3
print(rest)  # Output: ['a', 'b', 'c']
1
1 2 3
['a', 'b', 'c']

💡 Tip: Remember that tuples are immutable, so you cannot change their elements after creation. However, if a tuple contains mutable elements like lists, those elements can be modified.

❓ Which of the following operations can be performed on a list but not on a tuple?

❓ What is the output of the following code: my_tuple = (1, 2, 3); print(my_tuple[1])?

# Advanced example for Data Structures
# Production-ready pattern
print('Advanced implementation')
Advanced implementation

💡 Tip: Pro Tip: Master Data Structures thoroughly before moving to advanced topics. This foundation is crucial for writing professional Python code.

← Previous Continue interactively → Next →

Related Courses