Manipulate Lists in Python

PythonBeginner
Practice Now

Introduction

In this lab, you will gain hands-on experience manipulating lists in Python. Lists are a fundamental data structure for storing ordered collections of items. You will learn how to create, access, add, remove, and modify list elements.

Furthermore, this lab will guide you through more advanced operations such as sorting, querying, and nesting lists. By the end of this lab, you will have a solid understanding of how to effectively work with lists to manage and process data in your Python programs.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 100% completion rate. It has received a 100% positive review rate from learners.

Create and Access Lists

In this step, you will learn how to create lists and access their elements. Lists are ordered, mutable collections of items and are one of Python's most versatile data types.

Lists are created using square brackets [], with items separated by commas. Let's start by creating a few lists.

In the WebIDE file explorer on the left, find and open the file list_creation.py located in the ~/project directory. Add the following code to the file:

## Create an empty list
empty_list = []
print("Empty list:", empty_list)
print("Type of empty_list:", type(empty_list))

## Create a list of numbers
numbers = [10, 20, 30, 40, 50]
print("Numbers list:", numbers)

## Lists can contain elements of different data types
mixed_list = [1, 'hello', 3.14, True]
print("Mixed data type list:", mixed_list)

## You can also create a list from another iterable, like a string
string_list = list("python")
print("List from a string:", string_list)

After adding the code, save the file. To run the script, open the integrated terminal in the WebIDE and execute the following command:

python ~/project/list_creation.py

You should see the following output, demonstrating different ways to create a list:

Empty list: []
Type of empty_list: <class 'list'>
Numbers list: [10, 20, 30, 40, 50]
Mixed data type list: [1, 'hello', 3.14, True]
List from a string: ['p', 'y', 't', 'h', 'o', 'n']

Next, let's explore how to access elements within a list. You can access elements by their index (position). List indexing starts at 0. You can also use negative indices, where -1 refers to the last element.

Slicing allows you to access a range of elements. The syntax is list[start:stop:step].

Add the following code to the end of your list_creation.py file:

## Accessing list elements
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi']
print("\n--- Accessing Elements ---")
print("Fruits list:", fruits)

## Access the first element (index 0)
print("First element:", fruits[0])

## Access the last element (index -1)
print("Last element:", fruits[-1])

## Slicing: get elements from index 1 up to (but not including) index 4
print("Slice [1:4]:", fruits[1:4])

## Slicing: get all elements from the beginning up to index 3
print("Slice [:3]:", fruits[:3])

## Slicing: get all elements from index 2 to the end
print("Slice [2:]:", fruits[2:])

## Slicing: get a copy of the entire list
print("Slice [:] (a copy):", fruits[:])

## Slicing with a step: get every second element
print("Slice [::2]:", fruits[::2])

## Slicing to reverse the list
print("Reversed list [::-1]:", fruits[::-1])

Save the file and run the script again from the terminal:

python ~/project/list_creation.py

Observe the new output to understand how indexing and slicing work:

Empty list: []
Type of empty_list: <class 'list'>
Numbers list: [10, 20, 30, 40, 50]
Mixed data type list: [1, 'hello', 3.14, True]
List from a string: ['p', 'y', 't', 'h', 'o', 'n']

--- Accessing Elements ---
Fruits list: ['orange', 'apple', 'pear', 'banana', 'kiwi']
First element: orange
Last element: kiwi
Slice [1:4]: ['apple', 'pear', 'banana']
Slice [:3]: ['orange', 'apple', 'pear']
Slice [2:]: ['pear', 'banana', 'kiwi']
Slice [:] (a copy): ['orange', 'apple', 'pear', 'banana', 'kiwi']
Slice [::2]: ['orange', 'pear', 'kiwi']
Reversed list [::-1]: ['kiwi', 'banana', 'pear', 'apple', 'orange']

You have now learned how to create lists and access their contents.

Modify Lists: Adding, Removing, and Changing Elements

In this step, you will learn how to modify lists. Since lists are mutable, you can add, remove, or change their elements after they have been created.

First, let's focus on adding elements. Python provides several methods:

  • append(): Adds a single element to the end of the list.
  • extend(): Adds all elements from an iterable (like another list) to the end.
  • insert(): Adds an element at a specific index.

Open the file list_modification.py from the WebIDE file explorer. Add the following code to it:

## --- Adding Elements ---
my_list = [1, 2, 3]
print("Original list:", my_list)

## Add an element using append()
my_list.append(4)
print("After append(4):", my_list)

## Add multiple elements using extend()
my_list.extend([5, 6])
print("After extend([5, 6]):", my_list)

## Insert an element at a specific position
my_list.insert(1, 1.5) ## Insert 1.5 at index 1
print("After insert(1, 1.5):", my_list)

Save the file and run it from the terminal:

python ~/project/list_modification.py

Your output should show the list growing with each operation:

Original list: [1, 2, 3]
After append(4): [1, 2, 3, 4]
After extend([5, 6]): [1, 2, 3, 4, 5, 6]
After insert(1, 1.5): [1, 1.5, 2, 3, 4, 5, 6]

Next, let's practice removing elements. Key methods include:

  • remove(): Removes the first occurrence of a specified value.
  • pop(): Removes and returns the element at a given index (or the last element if no index is specified).
  • del: A statement to remove an item or slice by index.
  • clear(): Removes all elements from the list.

Add the following code to the end of list_modification.py:

## --- Removing Elements ---
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple']
print("\n--- Removing Elements ---")
print("Original fruits list:", fruits)

## Remove the last element using pop()
popped_item = fruits.pop()
print("After pop():", fruits)
print("Popped item:", popped_item)

## Remove an element by its value using remove()
fruits.remove('pear')
print("After remove('pear'):", fruits)

## Remove an element by its index using del
del fruits[1] ## Deletes 'apple' at index 1
print("After del fruits[1]:", fruits)

## Clear all elements from the list
fruits.clear()
print("After clear():", fruits)

Finally, you can change existing elements by assigning a new value to an index or a slice. Add this last block of code to list_modification.py:

## --- Changing Elements ---
letters = ['a', 'b', 'c', 'd', 'e']
print("\n--- Changing Elements ---")
print("Original letters list:", letters)

## Change a single element
letters[0] = 'A'
print("After changing index 0:", letters)

## Change a slice of elements
letters[1:3] = ['B', 'C']
print("After changing slice [1:3]:", letters)

Save the file and run the script one more time:

python ~/project/list_modification.py

The full output will demonstrate all the modification techniques you've learned:

Original list: [1, 2, 3]
After append(4): [1, 2, 3, 4]
After extend([5, 6]): [1, 2, 3, 4, 5, 6]
After insert(1, 1.5): [1, 1.5, 2, 3, 4, 5, 6]

--- Removing Elements ---
Original fruits list: ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple']
After pop(): ['orange', 'apple', 'pear', 'banana', 'kiwi']
Popped item: apple
After remove('pear'): ['orange', 'apple', 'banana', 'kiwi']
After del fruits[1]: ['orange', 'banana', 'kiwi']
After clear(): []

--- Changing Elements ---
Original letters list: ['a', 'b', 'c', 'd', 'e']
After changing index 0: ['A', 'b', 'c', 'd', 'e']
After changing slice [1:3]: ['A', 'B', 'C', 'd', 'e']

You are now proficient at adding, removing, and changing elements in a Python list.

Advanced List Operations: Sorting, Querying, and Nesting

In this final step, you will explore more advanced list operations, including sorting, querying for information, and working with nested lists.

Let's start with sorting. The sort() method modifies the list in-place. You can sort in ascending or descending order.

Open the file list_operations.py in the WebIDE. Add the following code to demonstrate sorting:

## --- Sorting Lists ---
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
print("--- Sorting Lists ---")
print("Original numbers list:", numbers)

## Sort the list in-place (ascending)
numbers.sort()
print("After sort():", numbers)

## Sort the list in descending order
numbers.sort(reverse=True)
print("After sort(reverse=True):", numbers)

## The reverse() method simply reverses the order, it does not sort
letters = ['a', 'b', 'c', 'd']
print("\nOriginal letters list:", letters)
letters.reverse()
print("After reverse():", letters)

Save the file and run it from the terminal:

python ~/project/list_operations.py

The output shows the sorted and reversed lists:

--- Sorting Lists ---
Original numbers list: [3, 1, 4, 1, 5, 9, 2, 6]
After sort(): [1, 1, 2, 3, 4, 5, 6, 9]
After sort(reverse=True): [9, 6, 5, 4, 3, 2, 1, 1]

Original letters list: ['a', 'b', 'c', 'd']
After reverse(): ['d', 'c', 'b', 'a']

Next, let's query a list to find information.

  • count(): Returns the number of times a value appears.
  • index(): Returns the index of the first occurrence of a value.

Add the following code to list_operations.py:

## --- Querying Lists ---
fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
print("\n--- Querying Lists ---")
print("Fruits list:", fruits)

## Count the occurrences of an element
apple_count = fruits.count('apple')
print("Count of 'apple':", apple_count)

## Find the index of the first occurrence of an element
banana_index = fruits.index('banana')
print("Index of first 'banana':", banana_index)

Finally, let's look at nested lists. A nested list is a list that contains other lists as its elements. This is useful for creating 2D structures like a matrix or a grid.

Add this final block of code to list_operations.py:

## --- Nested Lists ---
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
print("\n--- Nested Lists ---")
print("Matrix:", matrix)

## Access an entire inner list (a row)
first_row = matrix[0]
print("First row:", first_row)

## Access a specific element in the nested list
## To get the element '6', we access row 1, then column 2
element = matrix[1][2]
print("Element at matrix[1][2]:", element)

Save the file and run the script for the last time:

python ~/project/list_operations.py

The complete output will demonstrate sorting, querying, and nested list access:

--- Sorting Lists ---
Original numbers list: [3, 1, 4, 1, 5, 9, 2, 6]
After sort(): [1, 1, 2, 3, 4, 5, 6, 9]
After sort(reverse=True): [9, 6, 5, 4, 3, 2, 1, 1]

Original letters list: ['a', 'b', 'c', 'd']
After reverse(): ['d', 'c', 'b', 'a']

--- Querying Lists ---
Fruits list: ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
Count of 'apple': 2
Index of first 'banana': 3

--- Nested Lists ---
Matrix: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
First row: [1, 2, 3]
Element at matrix[1][2]: 6

You have now mastered several advanced techniques for working with Python lists.

Summary

In this lab, you have learned the fundamentals of manipulating lists in Python. You started by creating lists using square brackets [] and the list() constructor. You practiced accessing list elements with indexing and slicing, which are essential for retrieving specific items or subsets of a list.

You then explored how to modify lists by adding elements with append(), extend(), and insert(), removing elements with remove(), pop(), and del, and changing elements via index and slice assignment. Finally, you covered advanced operations, including in-place sorting with sort(), reversing with reverse(), querying with count() and index(), and structuring data with nested lists. You are now well-equipped to use lists effectively in your Python projects.