In Python, a list is a data type in which you can store multiple items.
To create a list, separate elements with commas in between square brackets.
For example, here is a list of integers:
numbers = [1, 2, 3, 4, 5]
To access list elements, use the square-bracket accessing operator [] with the index of the item. Also notice that the index starts from 0.
For example, let’s get the 1st and the 2nd element of a list:
numbers = [1, 2, 3, 4, 5] first = numbers[0] second = numbers[1] print(first) print(second)
Output:
1 2
To iterate over a list, you can use a for loop.
For example, let’s print each number in a list separately:
numbers = [1, 2, 3, 4, 5] for number in numbers: print(number)
Output:
1 2 3 4 5
This is a complete guide on lists in Python.
In this guide, you learn everything you need to know about lists starting from creating one.
Introduction to Lists
A list is one of the most commonly used data types in Python.
It is a mutable (changeable) and ordered sequence of elements.
A list element is commonly referred to as an element, item, value, or object.
These terms are used interchangeably in this tutorial similar to other guides on the internet.
Why Are Lists Useful?
Practically all programs have to deal with a bunch of related values. For instance, a course app might deal with student objects and grades. A weather app can deal with a bunch of locations and weather data.
In Python, you can use lists to store multiple related values in one place for easy access.
Lists in Python are useful for the same reason why pencil cases are useful in real life. You can store related items in the same logical place.
By using lists, your program becomes cleaner and more structured.
Also, lists let you perform all kinds of practical operations to its elements.
For example, you can easily:
- Calculate the length of a list.
- Sort a list.
- Find a specific value.
- Add, update, and delete values.
And much more.
To get a first impression of lists in Python, let’s start by creating one.
How to Create a List
To create a list in Python, place the elements inside square brackets and separate them by commas.
For example, here is a list of strings:
names = ["Alice", "Bob", "Charlie"]
This is a list of strings.
Each element in this list is a string that represents the name of a person.
Usually, it is a good idea to store elements of the same data type in a list.
For instance, a list of integers, strings, or booleans.
However, this is not a restriction.
In Python, you can store different types of data into the same list.
For instance, let’s create a list that has integers, strings, and booleans:
mixed = [0, True, "Charlie", 100, False, 9732]
This is a perfectly valid list in Python.
However, as stated before, it is usually a good idea to only store one type of data in the same list.
Length of a List
One of the important properties of a list is its length.
This can be useful for many reasons. For instance, the length of the list reveals how much data you are dealing with.
Later on, you see an example of how to use the length of a list to iterate over its elements.
In Python, there is a built-in function called len(). You can use this function to calculate the length of a list.
For example, let’s calculate the number of names in a list of strings:
names = ["Alice", "Bob", "Charlie"] length = len(names) print(length)
Output:
3
Good job!
Now you understand how to create a list and count the number of elements in it.
Next, let’s talk about accessing the elements of a list.
How to Access List Items
The reason why you insert elements into a list is to store them for easy access later on.
Without being able to access list elements, a list would be a useless data structure.
In Python, accessing the list elements is possible by using the square brackets accessing operator [].
Here is the syntax:
list[index]
Where:
- list is a list of items.
- index is the index of the item to access.
You are going to see a bunch of examples in the next sections.
Before that, it is important to learn how indexing works in Python. This is because accessing an element depends on its index.
Indexing in Python
In Python, each element in a list is associated with a unique index.
This index can be used to access that particular element.
Python uses zero-based indexing.
In other words, the indexing starts from 0 and grows from left to right.
This applies to lists as well as other types of iterables.
As a matter of fact, most programming languages use zero-based indexing.
When dealing with lists in Python, zero-based indexing means:
- 1st element has an index of 0.
- 2nd element has an index of 1
- 3rd element has an index of 2.
And so on.
This usually causes headaches, especially for beginners.
Let’s see examples of accessing list elements with the index.
As a first example, let’s create a list of strings and access the 3rd element:
names = ["Alice", "Bob", "Charlie", "David", "Eric"] thirdName = names[2] print(thirdName)
Output:
Charlie
As you can see, this piece of code returns the 3rd name, that is, Charlie.
This is because index 2 refers to item number 3.
Problems with Indexing
Zero-based indexing is commonly a root cause of one of the most common errors in Python, the List Index out of Range error.
This error occurs when you try to access an element with an index that overshoots the list.
Let me show you an example:
numbers = [1, 2, 3, 4, 5] last = numbers[5] print(last)
Output:
Traceback (most recent call last): File "<string>", line 2, in <module> IndexError: list index out of range
In this piece of code, you try to access the 6th element of the list even though there are only 5 elements.
This causes an error that says the list index is out of the range.
To fix this, you need to recall that Python uses zero-based indexing. You should thus use an index that is one less than the actual position of the element.
Next, let’s talk about negative indexing in Python.
Negative Indexing
Python also supports negative indexing that goes from right to left.
In Python, negative indexing starts at the index of -1 from the right-most element in a list.
In other words:
- The 1st element from the right has an index of -1
- The 2nd element from the right has an index of -2
- The 3rd element from the right has an index of -3
And so on.
Using negative indexing can be helpful if you want to access elements from right to left.
For example, if you are instructed to get the second last element in a list, you can use the index -2.
For example:
names = ["Alice", "Bob", "Charlie", "David", "Eric"] secondLast = names[-2] print(secondLast)
Output:
David
The negative indexing does not start from 0 because the 0th index is reserved for the 1st element in the positive zero-based indexing.
Now you understand how the list indexing works in Python.
The next section teaches you how to access multiple items of a list in one go.
Slicing Lists
In Python, you can access a bigger chunk of a list by using what is called slicing.
For instance, to get the first four items of a list, use slicing instead of manually accessing all four items separately.
The most basic way to use slicing is to access elements from a start index until an end index.
list[start:end]
Where:
- start is the zero-based starting index of the slice
- end is the exclusive end index of the slice. The item at the index end is not taken into the result.
For example, let’s access the 3 middle-most items in a list:
names = ["Alice", "Bob", "Charlie", "David", "Eric"] firstNames = names[1:4] print(firstNames)
Output:
['Bob', 'Charlie', 'David']
Here the slicing starts at index 1, which is the 2nd element of the list. The slicing continues until it encounters the item at index 4 (5th element) which is excluded.
If you leave out the start parameter when slicing, the slicing automatically starts at the first element of the list.
If you omit the end parameter, the slicing automatically continues to the end of the list.
For example:
numbers = [1, 2, 3, 4, 5] first3 = numbers[:3] last3 = numbers[2:] print(first3) print(last3)
Output:
[1, 2, 3] [3, 4, 5]
Another way to do slicing is by specifying one more parameter, that is, the step size.
list[start:end:step]
Here the start and end parameters work as described previously. The step parameter determines the number of elements to step over in the slice.
For example, let’s access every second element in a list:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] everySecond = numbers[::2] print(everySecond)
Output:
[1, 3, 5, 7, 9]
Because we omitted the start and end parameters, the slicing starts from the first element and ends at the last one. The step size of 2 makes the slice only include every second element in the list.
The step parameter can also be negative. This inverts the direction of slicing.
For example, let’s reverse a list:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] rev = numbers[::-1] print(rev)
Output:
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
In addition to negative step size, you can also use negative start and end parameters.
For example, let’s grab the last three values of a list:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(numbers[-4:-1])
Output:
[7, 8, 9]
If you are interested, feel free to read an ultimate guide about slicing in Python.
Next, let’s talk about looping through a list. This is one of the most common operations performed on a list.
Looping Through a List
When you have stored items in a list, you usually want to perform an action for each of those.
This operation could mean displaying the values, performing a math operation, checking a condition, or anything of that sort.
In the last chapter, you learned how to access elements of a list.
However, if you have hundreds of items on a list, you do not want manually perform actions on those.
This is where looping comes in useful.
In Python, you can use a loop to iterate over the list of values.
There are two types of loops at your disposal:
- For loops.
- While loops.
In the following sections, you are going to learn how to use both types of loops to iterate over lists.
For Loop
In Python, a for loop is used to iterate over an iterable collection of values, such as a list.
Here is the general syntax of a for loop:
for item in list: # actions
The for loop works such that it takes each element in a list at a time and assigns it to a variable called item. The area after the colon is calledthe body of the loop. Here you can run any valid Python code on the list item for example.
To understand how it works, you need to see some examples.
As a first example, let’s create a list of strings and print each string to the console:
names = ["Alice", "Bob", "Charlie", "David", "Eric"] for name in names: print(name)
Output:
Alice Bob Charlie David Eric
Here each string in the list is assigned to a variable called name one by one. Then you use the name to print it into the console.
As another example, let’s square each number in the list and show the result:
numbers = [1, 2, 3, 4, 5] for number in numbers: number = number ** 2 print(number)
Output:
1 4 9 16 25
Notice that this piece of code does not modify the original list.
Instead, each time you call number = number ** 2 you modify the copy of the actual number in the list.
Here is how a for loop works behind the scenes when looping through a list:
Loop with Index: The enumerate() Function
In the previous examples, you learned how to use a for loop to loop through a list of elements.
But what if you want to know the position of the element too?
In this case, you need to couple each list element with an index.
In Python, there is a built-in function enumerate() that does it.
The enumerate() function takes a list and assigns an index to each element. The result is a collection of item, index pairs.
Here is the general syntax of using the enumerate() function:
for index, item in enumerate(list): # actions
The index is the current element’s position in the list whereas the item is the element itself. You can use both of these variables inside the loop.
The best way to see this in action is by taking a look at an example.
For instance, let’s print the order of people in a line:
names = ["Alice", "Bob", "Charlie", "David", "Eric"] for index, name in enumerate(names): print(f"{index}: {name}")
Output:
0: Alice 1: Bob 2: Charlie 3: David 4: Eric
Using the enumerate() function is useful when you want to loop through a list and know the index of each element.
This prevents you from having to specify a separate variable to keep track of the index. This reduces the amount of code and improves readability.
In case you are curious, you can check a more detailed guide to the enumerate() function in Python.
List Comprehensions: Shorthand For Loops
In the earlier sections, you saw examples of for loops that spread across multiple lines.
But there is a neat little shorthand you can use to compress for loops into one-liner expressions.
This shorthand is called list comprehension.
Here is a visualization of how to turn a regular for loop into a comprehension:
Let me show you an example.
Let’s square a list of numbers using a list comprehension:
numbers = [1, 2, 3, 4, 5] squared = [number ** 2 for number in numbers] print(squared)
Output:
[1, 4, 9, 16, 25]
Here you only needed one line of code to get the job done.
A word of warning: Keeping it short isn’t always good! If you can convert a regular for loop to a list comprehension without sacrificing the code readability, feel free to do so! However, if the code becomes less understandable, it makes no sense to use comprehensions.
It is not wrong to never use comprehensions.
However, list comprehensions are used commonly so you have to understand them.
By the way, there is a lot more to for loops than you saw in this section.
In case you are interested, here is a complete guide to for loops in Python.
Anyway, the next section teaches you about while loops which is another main loop type in Python.
While Loop
While loop is the other basic loop type in Python.
Unlike a for loop, a while loop repeats actions as long as a condition True.
One application of a while loop is to loop through a list.
To loop through a list using a while loop, you need to keep track of the index of the current item. Furthermore, you need to continue the loop as long as the index is less than the length of the list.
Inside the loop, you can use the index to access the list elements.
Here is a blueprint for a while loop with lists:
index = 0 while index < len(list): # actions index = index + 1
The while loop continues as long as the index is less than the length of the list. It is thus important to update the index at each iteration!
For example, let’s print a list of strings using a while loop:
names = ["Alice", "Bob", "Charlie", "David", "Eric"] i = 0 while i < len(names): print(names[i]) i += 1
Output:
Alice Bob Charlie David Eric
This is a really basic example of a while loop.
Here the variable i is used to keeping track of the index of the loop.
The while loop prints out each element with the corresponding index and updates the index for the next round.
A common reason to perform a while loop on a list is to bulk-modify the list elements.
Let’s demonstrate this by squaring a list of numbers:
numbers = [1, 2, 3, 4, 5] i = 0 while i < len(numbers): numbers[i] **= 2 i += 1 print(numbers)
Output:
[1, 4, 9, 16, 25]
Word of warning: Using while loops, it is important not to cause an endless loop (condition is always True). To prevent this, always update the looping condition in each iteration.
To iterate a list, use for loops instead of while loops as much as you can.
This is because the for loop syntax is easier to read and not susceptible to endless loops.
In the next section, you are going to learn a bunch of ways to add an item or items to a list.
How to Add Elements to a List
In Python, a list is a mutable collection of values.
In short, the mutability of a list means you can add elements to a list.
As you can imagine, being able to add items to a list is a must-have feature.
Read more about mutability in Python.
Adding elements to a list can mean one of the following:
- Add to the end of a list (to the right-hand side).
- Add to the front of a list (to the left-hand side).
- Add multiple elements to the end of a list.
- Add multiple elements to the front of a list.
The next four sections teach you more about these options.
Add an Element to the End of a List
Perhaps the most common way to add an element to a list is by adding it to the end of the list.
This process is called appending.
In Python, a list has a built-in append() method that lets you add an element to the end of a list.
list.append(item)
The append() method takes an item as an argument and adds it to the end of the original list.
For instance:
numbers = [1, 2, 3] numbers.append(4) print(numbers)
Output:
[1, 2, 3, 4]
Add an Element to the Beginning of a List
A less common, but still useful action is to add an element to the beginning of a list.
To do this, you can use the insert() method.
list.insert(index, item)
Where:
- index is the index at which you want to add an item.
- item is the item to be added to the original list.
This allows you to add an element anywhere in the list. Thus, you can use it to add an element to the beginning of the list.
For example:
numbers = [1, 2, 3] numbers.insert(0, 100) print(numbers)
Output:
[100, 1, 2, 3]
Add Elements to the End of a List
In the previous two chapters, you learned how to add a single item to a list.
But sometimes it can be useful to add multiple elements to a list at the same time.
To add elements to the end of a list, use the extend() method.
This method takes a list as an argument and adds each element in the list to the end of the original list.
For example:
numbers = [1, 2, 3] numbers.extend([4, 5, 6, 7]) print(numbers)
Output:
[1, 2, 3, 4, 5, 6, 7]
Notice that the extend() method argument can be any other iterable, such as a tuple or string.
For example:
characters = ["H", "e", "l", "l", "o"] word = "world" characters.extend(word) print(characters)
Output:
['H', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
A string is an iterable collection of characters. When you pass a string to the extend() method, it takes each character and adds it to the end of a list.
Add Elements to the Beginning of a List
Last but least, it can be useful to know how to add elements to the beginning of a list.
This is not the most usual operation to perform and there is no dedicated method for doing this.
Instead, you can use the + operator to combine the two lists.
This creates a new list which you can assign back to the original one.
For example, let’s add a list of numbers from 1 to 3 to the beginning of a list from 4 to 6:
numbers = [4, 5, 6] oneToThree = [1, 2, 3] numbers = oneToThree + numbers print(numbers)
Output:
[1, 2, 3, 4, 5, 6]
How to Modify List Items
In Python, you can modify list elements by accessing an element with an index and assigning a new value to it.
As you can imagine, being able to modify list elements is a crucial task because it allows you to change data.
For example, let’s change the first number of a list of numbers:
numbers = [1, 2, 3] numbers[0] = 50 print(numbers)
Output:
[50, 2, 3]
How to Remove List Items
Similar to adding elements to a list, you can remove elements from a list.
Removing list elements can refer to any one of these:
- Remove the last item.
- Remove an item with a specific index.
- Remove an item with a specific value.
- Remove all items with a specific value.
- Remove all items.
The next five sections teach you how to handle each of these situations.
Remove the Last Item from a List
In Python, you can remove the last item of a list by using a built-in pop() method.
For example, let’s remove the last number in a list of numbers:
numbers = [1, 2, 3] numbers.pop() print(numbers)
Output:
[1, 2]
Notice that this method returns the removed element. This can be useful if you want to operate on the removed element.
For example, let’s remove a value and show it in the console:
numbers = [1, 2, 3] last = numbers.pop() print(last) print(numbers)
Output:
3 [1, 2]
Remove an Item with a Specific Index
In Python, the pop() method can also be used to remove any element with a given index in a list.
The pop() method takes an optional index argument that removes the element corresponding to that index.
For example, let’s remove the first element of a list:
numbers = [1, 2, 3] numbers.pop(0) print(numbers)
Output:
[2, 3]
Remove an Item with a Specific Value
In the previous sections, you learned how to remove values from a list by index.
However, sometimes you want to remove an item based on its value instead of the index.
To remove an element with a specific value, use the remove() method.
list.remove(value)
The remove() method removes the first occurrence of the value in a list.
For instance, let’s remove the name “Bob” from a list of strings:
names = ["Bob", "Alice", "Charlie", "Eric", "David"] names.remove("Charlie") print(names)
Output:
['Bob', 'Alice', 'Eric', 'David']
If you have multiple items with the same value in a list, the remove() method only removes the first one!
For example:
names = ["Bob", "Bob", "Alice"] names.remove("Bob") print(names)
Output:
['Bob', 'Alice']
As you can see, there is still one “Bob” on the list.
To remove all occurrences, you need to use a different strategy as explained in the next section.
Remove All Items with a Specific Value
You cannot use the remove() method to remove multiple elements of the same value from a list.
But there are many other options you can use.
The simplest way is by using a loop.
For example, here is a list comprehension approach:
numbers = [1, 4, 4, 26, 4, 4, 8, 0, 4] target = 4 numbers = [number for number in numbers if number != target] print(numbers)
Output:
[1, 26, 8, 0]
This approach creates a new list in which the specific values are filtered out. Then the new list is assigned back to the original one.
If you want to modify the original list directly, then you can use a while loop.
How to Empty a List
Last but not least, sometimes you may want to clean the entire list.
To do this, you can assign the original list to an empty list:
numbers = [1, 2, 3] numbers = [] print(numbers)
Output:
[]
But you can also use the built-in clear() method:
numbers = [1, 2, 3] numbers.clear() print(numbers)
Output:
[]
Next, let’s talk about finding elements in a list.
How to Find an Element in a List
When you are dealing with big lists of data, you commonly want to find items with a specific value.
This can mean:
- You want to check if an element exists in a list.
- You want to access the index of the specific value.
Let’s take a closer look at each operation.
How to Check If a Value Exists in a List
If you only want to know if a list contains at least one element with a specific value, use the in operator.
For example, let’s check if numbers 3 and 100 exist in a list:
numbers = [1, 2, 3] print(3 in numbers) print(100 in numbers)
Output:
True False
How to Get the Index of a Specific Value in a List
Usually, you also care about the position of the specific item in addition to knowing it exists.
To get the first index of a specific value in a list, use the list.index() method.
For example, let’s find the index of “Bob” in a list of names:
names = ["Alice", "Bob", "Charlie", "David"] bobIndex = names.index("Bob") print(bobIndex)
Output:
1
If you have multiple items with the same value, the index() method returns the first index:
names = ["Alice", "Bob", "Bob", "Bob"] bobIndex = names.index("Bob") print(bobIndex)
Output:
1
In the above list, there are multiple “Bob” strings. However, only the index of the first one is returned by the index() method.
In the next section, you learn a technique to find all the indexes of a specific value.
Find All Indexes of a Specific Value in a List
To get all the indexes of a specific value in a list, you can use a loop or a list comprehension.
For example, here is a list comprehension to find all indexes of “Bob” in a list of names:
names = ["Alice", "Charlie", "Bob", "Bob", "Bob", "Charlie"] bobIndexes = [idx for idx, name in enumerate(names) if name == "Bob"] print(bobIndexes)
Output:
[2, 3, 4]
If the enumerate() part confuses you, scroll up to see what it does.
How to Merge Two Lists
In Python, you can merge two lists together by using the addition (+) operator.
This is convenient because it is syntactically clear as to what you are trying to accomplish.
list1 + list2
When you use the + operator to merge two lists, you are creating a new list that is a combination of the lists.
For example, let’s merge two lists of numbers:
part1 = [1, 2, 3] part2 = [4, 5, 6] combined = part1 + part2 print(combined)
Output:
[1, 2, 3, 4, 5, 6]
If you want to modify the original list directly, use the extend() method you learned earlier.
This method adds a list to the end of another.
For example:
part1 = [1, 2, 3] part2 = [4, 5, 6] part1.extend(part2) print(part1)
Output:
[1, 2, 3, 4, 5, 6]
This piece of code modified the original list, instead of creating a new list.
How to Copy a List
It is quite common for you to want to clone a Python list.
In Python, copying lists (and other objects) is not possible by using the assignment operator (=):
a = [1, 2, 3] aCopy = a
Instead, you have to use the copy.deepcopy() function.
The assignment operator (=) creates a new reference to the same object in memory.
This is a more complex topic and is out of the scope of this guide.
You can read more about copying lists in Python here.
The next section teaches you the very basics of copying lists in Python.
Why = Operator Does Not Work?
In Python, the assignment operator (=) creates a new reference to an existing object.
Here is a great illustration of what happens under the hood:
In the above scenario, you end up having two variables that refer to the same object in memory.
In other words, if you modify the elements of one of the lists, the other one changes too.
For example, let’s create a copy of a list and modify the original one:
a = [1, 2, 3] b = a a[0] = 10000 print(a) print(b)
Output:
[10000, 2, 3] [10000, 2, 3]
As you can see, both lists a and b changed. This is because both a and b refer to the same object.
This proves copying this way is not possible.
In the next section, you learn how to create an independent copy of a list in Python.
The deepcopy() Method
In Python, there is a specific built-in copy module that can be used to create true copies of objects.
To create a completely independent copy of a Python object, use the copy.deepcopy() module.
For example:
import copy a = [1, 2, 3] b = copy.deepcopy(a) a[0] = 10000 print(a) print(b)
Output:
[10000, 2, 3] [1, 2, 3]
As you can see, the copied list did not change. This means it is a truly independent copy of the original list.
Next, let’s go through useful list methods and functions.
Useful List Methods
An efficient programmer reuses existing code as much as possible.
When dealing with lists, there are lots of operations that you perform countless times.
Calculating the length of a list is one of those.
Even though you could implement a loop that counts the number of elements in a list, you should use the built-in len() function instead.
This saves your time and allows you to write less code.
A Python list comes with a bunch of practical methods you can use to perform some common tasks.
In this guide, you have seen a bunch of them already, such as the list.pop() or list.index() methods.
To top it off, here are two useful list methods we did not cover yet.
sort()
To sort a list in Python, use the sort() method.
By default, the sort() method sorts numbers in increasing order.
If you sort a list of strings, the strings are sorted in alphabetical order.
For example:
names = ["Charlie", "Alice", "Bob"] names.sort() print(names)
Output:
['Alice', 'Bob', 'Charlie']
Let’s also see an example of sorting numbers.
For example:
numbers = [3, 1, 2, 8, 0, 23] numbers.sort() print(numbers)
Output:
[0, 1, 2, 3, 8, 23]
Read more about sorting in Python.
reverse()
In Python, you can reverse the ordering of a list by using the reverse() method.
For example, let’s reverse the ordering of a list of numbers:
numbers = [1, 2, 3, 4, 5] numbers.reverse() print(numbers)
Output:
[5, 4, 3, 2, 1]
In addition to list methods, there are also useful built-in functions you can use to make your life easier when working with lists.
Built-In List Functions
In addition to calling the methods of a list to perform useful operations, you can use built-in functions.
By the way, these functions are not restricted to working with lists. Instead, they can be called on other types of iterables, such as tuples as well.
In this section, you learn about the most useful built-in functions:
- min()
- max()
- sum()
- all()
- any()
min()
To find the smallest value in a list, you could use a for loop to iterate over each element and find the smallest item.
But there is a built-in function, min(), you can call on a list to get the job done.
The min() function takes a list as an argument. It then returns the smallest element in the list.
For example, let’s figure out the smallest number in a list:
numbers = [10, 2, -100, 4, 3, 19, 7] smallest = min(numbers) print(smallest)
Output:
-100
max()
Can you already guess what this function does?
In Python, you can use the built-in max() function to figure out the greatest element in a list.
For example, let’s find the biggest integer in a list of integers:
numbers = [10, 2, -100, 4, 3, 19, 7] biggest = max(numbers) print(biggest)
Output:
19
sum()
The sum() function calculates the sum of the list elements.
For example, let’s sum up all the integers of a list:
numbers = [10, 2, -100, 4, 3, 19, 7] total = sum(numbers) print(total)
Output:
-55
all()
In Python, the all() function checks if all the values of a list are True in a boolean context.
For example:
bools = [True, False, True] allTrue = all(bools) print(allTrue)
Output:
False
The result is False because one of the booleans is False. In other words, not all booleans in the list are True.
In Python, every data type has a corresponding boolean value.
For example, an integer of 0 is considered False, whereas 1 or any other integers are True.
This means you can call the all() function on a list of values other than booleans.
For example:
bools = [1, 0, 4, 7, 19] allZeros = all(bools) print(allZeros)
Output:
False
The result is False because there is one 0 in the list. In other words, there is one value that translates to False in a boolean context. Thus, not all the values are True as bools and the result is False.
any()
In Python, the built-in any() function checks if at least one of the list elements are True.
For example:
bools = [True, False, True] someTrue = any(bools) print(someTrue)
Output:
True
The result is True because there is at least one True in the list.
Similar to the all() function, the any() function can be called on a list with non-boolean elements. This is because all non-boolean values have a corresponding boolean value, as described in the previous section.
For example:
bools = [1, 0, 4, 7, 19] someNotZero = any(bools) print(someNotZero)
Output:
True
The result is True because there is at least one integer whose corresponding boolean value is True.
How to Find All List Functions and Methods in Python?
Thus far you have seen a bunch of list methods and functions in Python.
These are more than enough for you to work with lists efficiently.
However, it is good to understand there are more functions you can call on lists.
To see a list of all the list methods and functions, call the dir() function on a list:
If you take a look at the last bunch of elements in the list above, you can see some familiar names such as pop, append, and index. Those are all the built-in methods of a list.
But what are those methods with underscores?
Those are called double-underscore methods (dunder methods for short). They are methods that specify what happens when you call a corresponding function on the list.
For example, in the above list, there is a function called __len__. This is a special method implemented by a list that specifies what happens when someone calls the len() function on a list. With lists, it returns the length of the list.
You can call these special methods directly instead of using the built-in functions as an intermediary.
For example, let’s call both len() function and the __len__ method of a list:
numbers = [1, 2, 3] len1 = len(numbers) len2 = numbers.__len__() print(len1) print(len2)
Output:
3 3
Behind the scenes, the len() function runs the __len__ method of the list. Thus, they produce the exact same result.
The dunder methods are not a list-specific thing.
Other data types implement the same dunder methods, and you can implement them in your custom classes as well.
If you are confused by the dunder methods, I recommend watching this video. Even though it is an old video, the information is still relevant.
In addition to the dunder methods, there are other built-in functions you can call on lists and other iterables.
Here is a complete list of all the built-in functions in Python.
Conclusion
That is a lot of information about lists!
To recap, a list is one of the most commonly used data types in Python.
A list can be used to store data for later access. For example, a course application could store each student’s grades on a list.
You can easily add, update, and remove list elements.
Also, you can perform useful operations on lists, such as counting the length, finding a specific value, looping, and much more.
Thanks for reading.
Happy coding!