Skip to content

Lists and tuples are fundamental data structures in Python, used to store collections of data. They are essential building blocks for building complex programs and manipulating data efficiently. In this lesson, you will learn about the basics of lists and tuples, including how to create, access, modify, and iterate through them. You will also delve into the powerful concept of list comprehensions, a concise and expressive way to generate lists based on existing data. By the end of this lesson, you will have a solid understanding of lists and tuples and be able to use them effectively in your Python programming projects.

Learning Objectives

Upon completing this lesson, you will be able to:

  1. Define and differentiate between lists and tuples in Python.
  2. Create and initialize lists and tuples using different methods.
  3. Access individual elements of lists and tuples using indexing and slicing.
  4. Modify elements of lists using slicing, assignment, and methods like append() and insert().
  5. Iterate through lists and tuples using for loops and enumerate().
  6. Understand the concept of list comprehensions and their applications.
  7. Create lists using concise and expressive list comprehensions.
  8. Apply list comprehensions to filter, transform, and create new lists from existing data.

Key Concepts

Lists:

  • Lists are mutable, ordered collections of data elements.
  • Lists are enclosed in square brackets [].
  • Elements in a list can be accessed using indexing (e.g., list[index]).
  • List slicing allows for extracting a sublist based on start, end, and step indices.
  • Lists can be modified using assignment, methods like append() and insert(), and del operator.

Tuples:

  • Tuples are immutable, ordered collections of data elements.
  • Tuples are enclosed in parentheses ().
  • Elements in a tuple cannot be changed after creation.
  • Tuples can be used as keys in dictionaries and can be unpacked into multiple variables.

List Comprehensions:

  • List comprehensions are concise and expressive ways to create lists.
  • They use a concise syntax to define new lists based on existing data.
  • They are based on the concept of generators, which yield one element at a time.
  • List comprehensions can be used to filter, transform, and create new lists from existing data.

Understanding Lists and Tuples:

Lists and tuples are both data structures used to store collections of data. However, they differ in their mutability, meaning whether their elements can be modified after creation.

  • Lists: Lists are mutable, meaning their elements can be changed after they are created. They are enclosed in square brackets [] and can contain elements of any data type, including numbers, strings, booleans, and even other lists.

Example:

fruits = ["apple", "banana", "orange"]
fruits[1] = "grape"  # Modifying the second element
print(fruits)  # Output: ["apple", "grape", "orange"]
  • Tuples: Tuples are immutable, meaning their elements cannot be changed after they are created. They are enclosed in parentheses () and can contain elements of any data type.

Example:

numbers = (1, 2, 3, 4)
# Trying to modify elements will raise an error
# numbers[1] = 5
print(numbers)  # Output: (1, 2, 3, 4)

Accessing Elements in Lists and Tuples:

Both lists and tuples can be accessed using indexing and slicing. Indexing allows you to access individual elements using their position in the collection. Slicing allows you to extract a sublist based on specified start, end, and step indices.

Indexing:

names = ["Alice", "Bob", "Charlie"]
print(names[0])  # Output: Alice
print(names[2])  # Output: Charlie

Slicing:

letters = "Python"
print(letters[0:2])  # Output: Py
print(letters[-1])  # Output: n

Modifying Elements in Lists:

Lists can be modified using assignment, methods like append() and insert(), and del operator.

numbers = [1, 2, 3, 4]
numbers.append(5)  # Adding an element at the end
numbers.insert(2, 10)  # Inserting an element at index 2
del numbers[2]  # Deleting the element at index 2
print(numbers)  # Output: [1, 2, 10, 4]

Iterating through Lists and Tuples:

For loops can be used to iterate through the elements of lists and tuples. The enumerate() function can be used to access both the index and value of each element in the iteration.

for fruit in fruits:
    print(fruit)  # Output: apple, grape, orange

for index, number in enumerate(numbers):
    print(index, number)  # Output: 0 1, 1 2, 2 10, 3 4

List Comprehensions:

List comprehensions provide a concise and expressive way to create lists based on existing data. They use a generator-based syntax to iterate through the data and construct a new list based on specific criteria.

Generating Lists from Existing Lists:

squared_numbers = [number * number for number in numbers]
print(squared_numbers)  # Output: [1, 4, 100, 16]

Filtering and Transforming Data:

even_numbers = [number for number in numbers if number % 2 == 0]
uppercase_letters = [letter.upper() for letter in "hello"]
print(even_numbers)  # Output: [2, 4]
print(uppercase_letters)  # Output: HELLO

Hands-on Practice

Exercise 1:

Create a list of your favorite fruits and print the list.

Python

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

Exercise 2:

Access the second element from the list created in Exercise 1 and print it.

Python

second_fruit = fruits[1]
print(second_fruit)

Exercise 3:

Modify the list created in Exercise 1 by adding the fruit “grape” after the third element.

Python

fruits.insert(3, "grape")
print(fruits)

Exercise 4:

Create a list of numbers from 1 to 10 and print the list.

Python

numbers = list(range(1, 11))
print(numbers)

Exercise 5:

Iteratively calculate the sum of the numbers in the list created in Exercise 4 and print the result.

Python

sum_of_numbers = 0
for number in numbers:
    sum_of_numbers += number
print(sum_of_numbers)

Exercise 6:

Create a list comprehension to generate a list of squares of numbers from 1 to 10.

Python

squares = [number * number for number in range(1, 11)]
print(squares)

Exercise 7:

Create a list comprehension to filter a list of numbers between 1 and 100, including only even numbers.

Python

even_numbers = [number for number in range(1, 101) if number % 2 == 0]
print(even_numbers)

Exercise 8:

Create a list comprehension to transform a list of strings into uppercase letters.

Python

uppercase_letters = [letter.upper() for letter in "hello, world!"]
print(uppercase_letters)