Python Lists and Tuples

PythonBeginner
Practice Now

Introduction

Welcome to this hands-on lab on Python Lists and Tuples. Lists are one of the most fundamental and versatile data structures in Python, allowing you to store ordered collections of items. Tuples are similar but with a key difference: they are immutable.

Throughout this lab, you will learn how to create lists, access and manipulate their elements, and perform common operations like sorting and looping. You will also explore tuples and understand when to use them over lists.

This lab environment is a pre-configured WebIDE. All the necessary files for this lab have been created for you in the /home/labex/project directory. Let's get started.

Accessing List Elements

In this step, you will learn how to retrieve elements from a list using indexes and how to extract sublists using slicing. Lists are ordered collections of items enclosed in square brackets [].

First, open the file step1_access.py from the file explorer on the left. We will write our code in this file.

Note: If you are not familiar with using WebIDE (VS Code like), please learn it first at this lab.

Getting Values with Indexes

List elements are accessed using a zero-based index, meaning the first element is at index 0.

Add the following code to step1_access.py to create a list and access its first element:

## step1_access.py

furniture = ['table', 'chair', 'rack', 'shelf']

## Access the first element (index 0)
print(furniture[0])

To run the script, open a terminal in the WebIDE and execute the following command:

python3 /home/labex/project/step1_access.py

You should see the first element of the list printed to the console.

Output:

table

Negative Indexes

You can also use negative indexes to access elements from the end of the list. Index -1 refers to the last element, -2 to the second-to-last, and so on.

Modify step1_access.py to access the last element:

## step1_access.py

furniture = ['table', 'chair', 'rack', 'shelf']

## Access the last element (index -1)
print(furniture[-1])

Run the script again:

python3 /home/labex/project/step1_access.py

Output:

shelf

Getting Sublists with Slices

Slicing allows you to get a sublist using the [start:end] syntax. The start index is inclusive, and the end index is exclusive.

Let's practice this. For your verification task, modify step1_access.py to create a list and print a slice of it. Replace the existing content with the following code:

## step1_access.py

furniture = ['table', 'chair', 'rack', 'shelf']

## Get a sublist from index 1 up to (but not including) index 3
sublist = furniture[1:3]
print(sublist)

Run the script to see the result:

python3 /home/labex/project/step1_access.py

Output:

['chair', 'rack']

You can also create a copy of a list using a full slice [:]. Any modifications to the original list will not affect the copy.

## step1_access.py

spam = ['cat', 'bat', 'rat', 'elephant']
spam2 = spam[:]  ## Create a shallow copy
spam.append('dog')

print(spam)
print(spam2)

Run the script:

python3 /home/labex/project/step1_access.py

Output:

['cat', 'bat', 'rat', 'elephant', 'dog']
['cat', 'bat', 'rat', 'elephant']

After you have successfully printed the ['chair', 'rack'] slice, click the Verify button to proceed to the next step.

Modifying and Manipulating Lists

In this step, you will explore how to manage and modify list content. This includes changing values, combining lists, and adding new elements.

Open the file step2_modify.py to begin.

Getting List Length with len()

The len() function returns the number of items in a list.

Add this code to step2_modify.py:

## step2_modify.py

furniture = ['table', 'chair', 'rack', 'shelf']
print(len(furniture))

Run the script:

python3 /home/labex/project/step2_modify.py

Output:

4

Changing Values with Indexes

You can change an element in a list by assigning a new value to its index.

## step2_modify.py

furniture = ['table', 'chair', 'rack', 'shelf']
furniture[0] = 'desk'  ## Change the first element
print(furniture)

Run the script:

python3 /home/labex/project/step2_modify.py

Output:

['desk', 'chair', 'rack', 'shelf']

Concatenation and Replication

You can combine two lists using the + operator (concatenation) or repeat a list's contents using the * operator (replication).

## step2_modify.py

list1 = [1, 2, 3]
list2 = ['A', 'B', 'C']
combined_list = list1 + list2
print(combined_list)

replicated_list = ['X'] * 3
print(replicated_list)

Run the script:

python3 /home/labex/project/step2_modify.py

Output:

[1, 2, 3, 'A', 'B', 'C']
['X', 'X', 'X']

Adding Values with append() and insert()

  • The append() method adds an item to the end of the list.
  • The insert() method adds an item at a specified index.

For your verification task, let's combine these operations. Replace the content of step2_modify.py with the following code. This script will create a list, add an element to the end, and insert another at the beginning.

## step2_modify.py

furniture = ['table', 'chair', 'rack', 'shelf']

## Add 'bed' to the end of the list
furniture.append('bed')

## Insert 'desk' at the beginning of the list (index 0)
furniture.insert(0, 'desk')

print(furniture)

Run the script to see the final modified list:

python3 /home/labex/project/step2_modify.py

Output:

['desk', 'table', 'chair', 'rack', 'shelf', 'bed']

Once your script produces the correct output, click Verify.

Removing Values and Sorting

In this step, you'll learn different ways to remove items from a list and how to sort a list's contents.

Please open the file step3_remove.py.

Removing Values

Python provides several ways to remove items from a list:

  • del statement: Removes an item at a specific index.
  • remove() method: Removes the first occurrence of a specific value.
  • pop() method: Removes and returns an item at a specific index (or the last item if no index is given).

Let's see them in action. Add this to step3_remove.py:

## step3_remove.py

furniture = ['table', 'chair', 'rack', 'shelf']
del furniture[2]  ## Removes 'rack'
print(furniture)

furniture.remove('chair') ## Removes 'chair'
print(furniture)

Run the script:

python3 /home/labex/project/step3_remove.py

Output:

['table', 'chair', 'shelf']
['table', 'shelf']

Sorting Values with sort()

The sort() method sorts the list in place. By default, it sorts in ascending order.

## step3_remove.py

numbers = [2, 5, 3.14, 1, -7]
numbers.sort()
print(numbers)

letters = ['a', 'z', 'A', 'Z']
letters.sort(key=str.lower) ## Case-insensitive sort
print(letters)

Run the script:

python3 /home/labex/project/step3_remove.py

Output:

[-7, 1, 2, 3.14, 5]
['a', 'A', 'z', 'Z']

For your verification task, you need to create a list, remove a specific item, and then sort the remaining items. Replace the content of step3_remove.py with the following:

## step3_remove.py

furniture = ['table', 'chair', 'rack', 'shelf']

## Remove the item 'rack'
furniture.remove('rack')

## Sort the list alphabetically
furniture.sort()

print(furniture)

Run the script to see the result:

python3 /home/labex/project/step3_remove.py

Output:

['chair', 'shelf', 'table']

After your script correctly removes and sorts the list, click Verify.

Looping and Advanced Techniques

In this step, you will master how to iterate through lists and use some advanced but highly useful list techniques.

Open the file step4_loop.py for this section.

Looping with for

A for loop is the standard way to iterate over the items in a list.

## step4_loop.py

furniture = ['table', 'chair', 'rack', 'shelf']

for item in furniture:
    print(item)

Run the script:

python3 /home/labex/project/step4_loop.py

Output:

table
chair
rack
shelf

Getting Index and Value with enumerate()

If you need both the index and the value during iteration, use the enumerate() function.

## step4_loop.py

furniture = ['table', 'chair', 'rack', 'shelf']

for index, item in enumerate(furniture):
    print(f'index: {index} - item: {item}')

Run the script:

python3 /home/labex/project/step4_loop.py

Output:

index: 0 - item: table
index: 1 - item: chair
index: 2 - item: rack
index: 3 - item: shelf

The in and not in Operators

These operators let you check if a value exists within a list.

## step4_loop.py

furniture = ['table', 'chair', 'rack', 'shelf']
print('rack' in furniture)
print('bed' not in furniture)

Run the script:

python3 /home/labex/project/step4_loop.py

Output:

True
True

Looping in Multiple Lists with zip()

The zip() function is perfect for processing multiple lists in parallel. It pairs up elements from each list.

For your verification task, you will use zip() to combine two lists. Replace the content of step4_loop.py with the following code. It will iterate over furniture items and their corresponding prices, printing a formatted string for each pair.

## step4_loop.py

furniture = ['table', 'chair', 'rack', 'shelf']
price = [100, 50, 80, 40]

for item, amount in zip(furniture, price):
    print(f'The {item} costs ${amount}')

Run the script to see the combined output:

python3 /home/labex/project/step4_loop.py

Output:

The table costs $100
The chair costs $50
The rack costs $80
The shelf costs $40

Once your script is working correctly, click Verify.

Understanding Tuples

In this final step, you will learn about the tuple data type. Tuples are similar to lists, but they are immutable, meaning their contents cannot be changed after creation.

Open the file step5_tuple.py.

The Tuple Data Type

Tuples are defined with parentheses () instead of square brackets. Because they are immutable, you cannot change, add, or remove elements after the tuple is created. This makes them more memory-efficient and useful for data that should not be altered.

You can access tuple elements using indexes and slices, just like with lists.

## step5_tuple.py

furniture = ('table', 'chair', 'rack', 'shelf')

## Accessing elements
print(furniture[0])

## Slicing
print(furniture[1:3])

## Getting length
print(len(furniture))

Run the script:

python3 /home/labex/project/step5_tuple.py

Output:

table
('chair', 'rack')
4

If you try to modify a tuple, Python will raise a TypeError. For example, furniture[0] = 'desk' would cause an error.

Converting Between list() and tuple()

You can easily convert between lists and tuples using the list() and tuple() constructor functions.

For your verification task, you will convert a list into a tuple. Replace the content of step5_tuple.py with the following code:

## step5_tuple.py

## A list of items
my_list = ['cat', 'dog', 5]

## Convert the list to a tuple
my_tuple = tuple(my_list)

print(my_tuple)

Run the script to see the resulting tuple:

python3 /home/labex/project/step5_tuple.py

Output:

('cat', 'dog', 5)

You can also convert a tuple back to a list if you need to modify it:

## step5_tuple.py

my_tuple = ('cat', 'dog', 5)
my_list = list(my_tuple)
print(my_list)

Run the script:

python3 /home/labex/project/step5_tuple.py

Output:

['cat', 'dog', 5]

Once your script successfully converts the list to a tuple and prints it, click Verify to complete the lab.

Summary

Congratulations on completing the lab! You have gained a solid understanding of Python's core data structures: lists and tuples.

You've learned how to:

  • Create lists and access elements using positive and negative indexes.
  • Extract sublists using slicing.
  • Modify lists by changing values, adding elements with append() and insert(), and removing them with del, remove(), and pop().
  • Sort lists in-place using the sort() method.
  • Iterate through lists effectively using for loops, enumerate(), and zip().
  • Understand the immutable nature of tuples and convert between lists and tuples.

These skills are fundamental for any Python programmer and will be invaluable in your future projects.