Lists
Lists
Lists
ipynb - Colab
keyboard_arrow_down Lists
Lists are an essential and fundamental data structure in programming. They serve as ordered
collections that enable you to store and organize multiple items in a structured manner.
keyboard_arrow_down Motivation
Welcome to your journey of learning about lists in programming! Let's explore the key reasons
why learning about lists is valuable:
Data Storage and Organization: Lists are like special containers that can hold lots of things
together. They help you store and organize different pieces of data in one place. It's like
having a box where you can keep your favorite snacks. Lists make it easier to keep track of
and work with collections of data.
Iterating and Manipulating Data: Lists allow you to do cool things with your data. You can
go through each item in the list and do something with it. You can change, add, or take
away things from the list, just like adding more snacks to your box. Lists give you the
power to work with data in many different ways.
Lists Creation
In Python, lists are created by enclosing elements within square brackets ( [] ), and each element
is separated by a comma. Lists can store elements of different types, including numbers, strings,
or even other lists. Here are a few examples of lists:
To create an empty list, you can use empty square brackets ( [] ), indicating that the list contains
no elements.
empty_list = []
apple
2. Mutable: Lists are mutable, meaning you can modify, add, or remove elements after the
list is created. This allows for dynamic changes to the list's content.
numbers = [1, 2, 3, 4, 5]
numbers[2] = 10
print(numbers) # Output: [1, 2, 10, 4, 5]
[1, 2, 10, 4, 5]
3. Heterogeneous Elements: Lists can contain elements of different data types. You can
have a mix of integers, strings, or even other lists within a single list.
4. Variable Length: Lists can grow or shrink dynamically as elements are added or
removed. They do not have a fixed size, allowing for flexibility in managing varying amounts
of data. We will see how to do that later in this lesson.
Indexing
Negative indexing: Lists also support negative indexing, where the index -1 refers to the
last element, -2 refers to the second-to-last element, and so on. Negative indices count
apple
banana
cherry
banana
Out-of-range indices: If you try to access an index that is outside the valid range of indices
for a list, you'll get an IndexError . It's important to ensure that the index is within the range
of the list to avoid such errors.
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
/Users/maya/Desktop/AiCore Work/Content-Projects/Content/units/Essentials/7. Python
programming/8. Lists/Notebook.ipynb Cell 6 in <cell line: 2>()
<a href='vscode-notebook-cell:/Users/maya/Desktop/AiCore%20Work/Content-
Projects/Content/units/Essentials/7.%20Python%20programming/8.%20Lists/Notebook.ipynb
line=0'>1</a> fruits = ["apple", "banana", "cherry"]
----> <a href='vscode-notebook-cell:/Users/maya/Desktop/AiCore%20Work/Content-
Projects/Content/units/Essentials/7.%20Python%20programming/8.%20Lists/Notebook.ipynb
line=1'>2</a> print(fruits[3])
In this example, the list fruits has three elements with indices 0 , 1 , and 2 . However, when we
try to access the element at index 3 using fruits[3] , it goes beyond the valid range of indices.
As a result, Python raises an IndexError indicating that the list index is out of range.
To avoid this error, you need to ensure that the index you're trying to access is within the valid
range of indices for the list. In this case, valid indices for fruits range from 0 to 2 (inclusive), so
accessing fruits[2] will give you the last element of the list without causing an IndexError .
keyboard_arrow_down Slicing
Slicing allows you to extract a portion of a list by specifying a range of indices. It creates a new
list containing the selected elements. The syntax for slicing is start_index : stop_index .
The start_index parameter in slicing denotes the index at which the slicing operation begins.
The element at the start_index is included in the slice. The stop_index parameter in slicing
denotes the index at which the slicing operation ends. The element at the stop_index is not
included in the slice.
numbers = [1, 2, 3, 4, 5]
sliced_list = numbers[1:4]
print(sliced_list) # Output: [2, 3, 4]
[2, 3, 4]
In the example above, numbers[1:4] returns a new list containing elements from index 1
(inclusive) to index 4 (exclusive), which are the elements [2, 3, 4] in the original list.
Omitting indices: When you omit the start_index in a slice, it defaults to 0 , and when you
omit the stop_index , it defaults to the length of the list.
numbers = [1, 2, 3, 4, 5]
print(numbers[:3]) # Output: [1, 2, 3]
print(numbers[2:]) # Output: [3, 4, 5]
print(numbers[:]) # Output: [1, 2, 3, 4, 5]
[1, 2, 3]
[3, 4, 5]
[1, 2, 3, 4, 5]
In the example above, numbers[:3] returns a new list containing the elements from the start of
the list up to index 3 . numbers[2:] returns a new list containing elements from index 2 to the
end of the list. numbers[:] returns a copy of the entire list.
To create a nested list, you can simply include lists as elements within another list. Here's an
example:
In the above example, nested_list contains three inner lists, each representing a row of values.
The outer list encapsulates these inner lists, forming a nested structure.
[1, 2, 3]
5
In the above example, nested_list[0] retrieves the first inner list [1, 2, 3] . To access the
value 5 within the second inner list, you use nested_list[1][1] .
In the above example, nested_list[1][0] represents the element 4 within the second inner list.
By assigning it a new value of 10 , we modify the nested list accordingly.
Concatenation ( + operator):
Lists can be concatenated using the + operator. It combines two or more lists into a single list,
preserving the order of elements.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
concatenated = list1 + list2
print(concatenated) # Output: [1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]
In this example, the + operator concatenates list1 and list2 , resulting in a new list named
concatenated .
Lists can be repeated or multiplied using the * operator. It creates a new list by repeating the
elements of the original list a specified number of times.
numbers = [1, 2, 3]
repeated = numbers * 3
print(repeated) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]
[1, 2, 3, 1, 2, 3, 1, 2, 3]
In this example, the * operator repeats the elements of the numbers list three times, creating a
new list named repeated .
You can test whether an element is present in a list using the in and not in operators. They
return a Boolean value ( True or False ) based on the presence or absence of the element in the
list.
True
True
In this example, the in operator checks if "banana" is present in the fruits list, returning True .
The not in operator checks if "orange" is not present in the fruits list, returning True .
Accessing Elements
You can access individual elements of a list using their index values. Indices start from 0 for the
first element and can be negative to access elements from the end of the list.
apple
cherry
append() method
The append() method is used to add an element to the end of a list. It takes a single argument,
which is the value to be added.
The insert() method allows you to add an element at a specific index within a list. It takes two
arguments: the index at which to insert the element and the value to be inserted.
In this example, the insert() method is used to add the value "orange" at index 1 in the
fruits list. The existing elements are shifted to accommodate the new element.
The extend() method allows you to add multiple elements from another list to the end of the
current list. It takes an iterable as an argument, such as another list or a string. Don't worry about
iterables for now as we will cover them in a later lecture, but for now just remember it is an
object that represents a collection of elements that can be accessed one by one.
In this example, the extend() method is used to add the elements from the more_fruits list to
the fruits list. The resulting list contains all the elements from both lists.
['apple', 'cherry']
Here's an example that demonstrates the usage of the remove() method and the ValueError
that is raised when the specified value is not found in the list:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
/Users/maya/Desktop/AiCore Work/Content-Projects/Content/units/Essentials/7. Python
programming/8. Lists/Notebook.ipynb Cell 24 in <cell line: 2>()
<a href='vscode-notebook-cell:/Users/maya/Desktop/AiCore%20Work/Content-
Projects/Content/units/Essentials/7.%20Python%20programming/8.%20Lists/Notebook.ipynb
line=0'>1</a> fruits = ["apple", "banana", "cherry"]
----> <a href='vscode-notebook-cell:/Users/maya/Desktop/AiCore%20Work/Content-
Projects/Content/units/Essentials/7.%20Python%20programming/8.%20Lists/Notebook.ipynb
line=1'>2</a> fruits.remove("grape")
In this example, we have a list called fruits containing three elements: "apple" , "banana" , and
"cherry" . When we try to remove the value "grape" using the remove() method, a ValueError
is raised. This error occurs because the value "grape" is not present in the list. The remove()
method expects the value to exist in the list and removes only the first occurrence of that value.
The pop() method removes an element at a given index from the list and returns its value. If no
index is specified, it removes and returns the last element. This method allows you to remove
elements from the list while also capturing their values for further processing.
30
[10, 20, 40, 50]
It's important to note that if you try to pop() an index that is out of range, an IndexError will be
raised. Make sure to provide a valid index within the range of the list to avoid this error.
numbers = [5, 2, 8, 1, 9]
numbers.sort()
print(numbers) # Output: [1, 2, 5, 8, 9]
[1, 2, 5, 8, 9]
['cherry', 'banana', 'apple']
In this example, the sort() method is used to sort the numbers list in ascending order and the
fruits list in descending order.
numbers = [1, 2, 3, 4, 5]
numbers.reverse()
print(numbers) # Output: [5, 4, 3, 2, 1]
[5, 4, 3, 2, 1]
numbers = [5, 2, 8, 1, 9]
print(min(numbers)) # Output: 1
print(max(numbers)) # Output: 9
1
9
The index() method allows you to find the index of a specific element within a list. It returns the
index of the first occurrence of the element in the list.
IndexError
An IndexError occurs when you try to access an index that is outside the valid range of indices
for a list. This typically happens when the index is negative or greater than or equal to the length
of the list.
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
/Users/maya/Desktop/AiCore Work/Content-Projects/Content/units/Essentials/7. Python
programming/8. Lists/Notebook.ipynb Cell 60 in <cell line: 2>()
<a href='vscode-notebook-cell:/Users/maya/Desktop/AiCore%20Work/Content-
Projects/Content/units/Essentials/7.%20Python%20programming/8.%20Lists/Notebook.ipynb
line=0'>1</a> fruits = ["apple", "banana", "cherry"]
----> <a href='vscode-notebook-cell:/Users/maya/Desktop/AiCore%20Work/Content-
Projects/Content/units/Essentials/7.%20Python%20programming/8.%20Lists/Notebook.ipynb
line=1'>2</a> print(fruits[3])
To troubleshoot an IndexError , ensure that the index you're trying to access is within the valid
range of indices for the list. Remember that list indices start from 0 and go up to len(list) -
1.
keyboard_arrow_down ValueError
A ValueError may occur when using methods like remove() or index() if the specified value is
not found in the list.
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
/Users/maya/Desktop/AiCore Work/Content-Projects/Content/units/Essentials/7. Python
programming/8. Lists/Notebook.ipynb Cell 62 in <cell line: 2>()
<a href='vscode-notebook-cell:/Users/maya/Desktop/AiCore%20Work/Content-
Projects/Content/units/Essentials/7.%20Python%20programming/8.%20Lists/Notebook.ipynb
line=0'>1</a> fruits = ["apple", "banana", "cherry"]
----> <a href='vscode-notebook-cell:/Users/maya/Desktop/AiCore%20Work/Content-
Projects/Content/units/Essentials/7.%20Python%20programming/8.%20Lists/Notebook.ipynb
line=1'>2</a> fruits.remove("orange")
To handle a ValueError , you should check if the value exists in the list before performing the
operation.
keyboard_arrow_down AttributeError
An AttributeError can occur when using incorrect or unsupported list operations or methods.
For example, attempting to sort a list that contains elements of different data types can result in
an AttributeError .
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/Users/maya/Desktop/AiCore Work/Content-Projects/Content/units/Essentials/7. Python
programming/8. Lists/Notebook.ipynb Cell 64 in <cell line: 2>()
<a href='vscode-notebook-cell:/Users/maya/Desktop/AiCore%20Work/Content-
Projects/Content/units/Essentials/7.%20Python%20programming/8.%20Lists/Notebook.ipynb
line=0'>1</a> fruits = ["apple", "banana", "cherry", 5]
----> <a href='vscode-notebook-cell:/Users/maya/Desktop/AiCore%20Work/Content-
Projects/Content/units/Essentials/7.%20Python%20programming/8.%20Lists/Notebook.ipynb
line=1'>2</a> fruits.sort()
To resolve an AttributeError , ensure that you're using the appropriate methods and operations
supported by lists. Check the documentation or the specific error message to identify the cause
of the error.
Troubleshooting Tips
Double-check your indices: Ensure that the indices you are using to access or modify list
elements are correct and within the valid range
Verify the presence of values: Before using methods like remove() or index() , confirm
that the value exists in the list to avoid ValueError
Check data types: If you encounter an AttributeError or unexpected behavior, review the
data types in your list and ensure they are compatible with the operations you're
performing
Print and debug: If you're unsure about the state of your list, print intermediate results or
use debugging techniques to identify any issues
By understanding these common list errors and following troubleshooting strategies, you can
handle and resolve issues that may arise while working with lists in Python.
Key Takeaways
Lists in Python are versatile data structures that allow you to store and manipulate
collections of items
Lists are declared using square brackets ( [] ), and they can contain elements of different
data types
Important list operations include concatenation ( + ), repetition ( * ), indexing ( [] ), slicing
( [:] ), length determination ( len() ), sorting ( sort() ), reversing ( reverse() ), finding the
minimum ( min() ) and maximum ( max() ) values, and joining elements into a string
( join() )
When working with lists, be mindful of common errors such as IndexError (accessing
indices out of range), ValueError (searching or removing non-existent values), and
AttributeError (using unsupported operations or methods)
Troubleshooting techniques for list errors include checking indices, verifying value
presence, reviewing data types, and utilizing print statements and debugging tools