What is a Python List?
A Python list is an ordered and changeable collection that allows duplicate members. List items can be different data types, as well as other lists (nested list).
List items are comma separated between a pair of square brackets []
. The list index starts at 0.
This guide is designed to walk you through how to use Python lists efficiently, with clear, commented code samples.
- Create a list
- Add items to a list
- Read from a list
- Python list comprehension
- Update a list
- Delete from a list
- Slicing Python lists
- Testing list membership
- List operators
- Built-in functions
- List methods
- List equality
- Create a list of lists
Create a List
There are 3 main ways to create a list in Python:
- Using the
list()
constructor - Placing a comma-separated collection of elements inside square braces
[]
- Concatenating two existing lists using the
+
operator, which forms a new list
Syntax: list(iterable)
# Create a list of strings using the list() constructor string_list = list(("val1", "val2", "val3", "val4")) print("string_list =", string_list) # Pass a single string to the list() constructor a = "TestString" print("a =", a) print("list(a) = ", list(a)) # For comparison, pass a single string to the set() constructor a = "TestString" print("set(a) = ", set(a))
Output:
string_list = ['val1', 'val2', 'val3', 'val4']
a = TestString
list(a) = ['T', 'e', 's', 't', 'S', 't', 'r', 'i', 'n', 'g']
set(a) = {'t', 'g', 'e', 'S', 's', 'T', 'n', 'i', 'r'}
The output above shows how the list()
constructor preserves the order of the string, whereas the set()
constructor does not.
# Create a list of strings string_list = ["val1", "val2", "val3"] print("string_list =", string_list) # Create a list containing values of multiple data types list1 = [1, "val1", 4.55, (2, 3, 4, 5)] print("list1 =", list1)
Output:
string_list = ['val1', 'val2', 'val3']
list1 = [1, 'val1', 4.55, (2, 3, 4, 5)]
# Confirmation that a list can contain duplicate items list1 = [1, 2, 2, 2, 3, 4] print("list1 =", list1)
Output:
list1 = [1, 2, 2, 2, 3, 4]
3. Concatenating using the +
operator
If you have two existing lists and you simply want to create a new list that’s a combination of their values, you can use the +
operator.
# Create two lists list1 = [1, 2, 3, 4] list2 = [4, 5, 6, 7] print("list1 =", list1) print("list2 =", list2) # Concatenate list1 and list2 using + list3 = list1 + list2 print("\nlist3 = list1 + list2") print("list3 =", list3)
Output:
list1 = [1, 2, 3, 4]
list2 = [4, 5, 6, 7]
list3 = list1 + list2
list3 = [1, 2, 3, 4, 4, 5, 6, 7]
Creating an empty list
If you need to create an empty list, you can use list[]
or list()
.
# Create two empty lists list1 = [] list2 = list() # Print our lists and check equality print("list1 =", list1) print("list2 =", list2) print("list1 == list2 is ", list1 == list2)
Output:
list1 = []
list2 = []
list1 == list2 is True
Add Items to a List
There are 3 main methods to add items to a list in Python:
append()
for adding single elementsextend()
for adding single or multiple elementsinsert()
for adding single or multiple elements
The append()
method can be used to add a single element to a list.
Syntax: list.append(elem)
# Create our initial list list1 = ["apple", "orange"] print("list1 =", list1) # Add a single item to list1 using append() list1.append("fruit") print("list1.append('fruit') =", list1) # Add a list as an element of list1 using append() list1.append([1, 2]) print("list1.append([1, 2]) =", list1)
Output:
list1 = ['apple', 'orange']
list1.append('fruit') = ['apple', 'orange', 'fruit']
list1.append([1, 2]) = ['apple', 'orange', 'fruit', [1, 2]]
2. Using extend()
The extend()
method can be used to add single or multiple elements to a list.
Syntax: list.extend(list2)
# Create our initial list list1 = ["apple", "orange", "pear"] print("list1 =", list1) # Add a single item to list1 using extend() list1.extend(["fruit"]) print("list1.extend(['fruit']) =", list1) # Add multiple items to list1 using extend() list1.extend(["grape", "banana"]) print("list1.extend(['grape', 'banana']) =\n", list1) # Add a list as an element of list1 using extend() list1.extend([[1, 2, 3, 4]]) print("list1.extend([[1, 2, 3, 4]]) =\n", list1)
Output:
list1 = ['apple', 'orange', 'pear']
list1.extend('fruit') = ['apple', 'orange', 'pear', 'fruit']
list1.extend(['grape', 'banana']) =
['apple', 'orange', 'pear', 'fruit', 'grape', 'banana']
list1.extend([[1, 2, 3, 4]]) =
['apple', 'orange', 'pear', 'fruit', 'grape', 'banana', [1, 2, 3, 4]]
Note: One important point worth mentioning is the importance of the square brackets []
as part of list.extend([iterable])
.
extend()
is essentially merging two lists. Not including the square bracket means Python applies the list()
constructor to it, thereby assigning each character in the string its own position in the list. This is highlighted in the example below.
# Create our initial list list1 = ["apple", "orange", "pear"] print("list1 =", list1) # Add a single item to list1 using extend() without square brackets list1.extend("fruit") print("list1.extend('fruit') =", list1) # Whereas adding the item using square brackets adds the full string as a single element list1 = ["apple", "orange", "pear"] list1.extend(["fruit"]) print("list1.extend(['fruit']) =", list1)
Output:
list1 = ['apple', 'orange', 'pear']
list1.extend('fruit') = ['apple', 'orange', 'pear', 'f', 'r', 'u', 'i', 't']
list1.extend(['fruit']) = ['apple', 'orange', 'pear', 'fruit']
3. Using insert()
The insert()
method adds a single element to the list at the given index. This shifts existing elements to the right, and modifies the existing list, rather than creating a new one.
Syntax: list.insert(index, elem)
# Create a list list1 = ["val1", "val2", "val3"] print("list1 =", list1) # Insert a single new element to the end of list1 list1.insert(4, "val4") print("list1.insert(4, 'val4') =", list1) # Insert a single new element to the middle of list1 list1.insert(2, "val5") print("list1.insert(2, 'val5') =", list1)
Output:
list1 = ['val1', 'val2', 'val3']
list1.insert(4, 'val4') = ['val1', 'val2', 'val3', 'val4']
list1.insert(2, 'val5') = ['val1', 'val2', 'val5', 'val3', 'val4']
Read from a List
There are 3 main ways to access elements in a list:
- Referring to the item using its index
- Iterating through the list using a
for
loop - Iterating through the list using a
while
loop
It’s important to remember that list indexes are zero-based. This means the first element appears at index 0, second element at index 1, and so on.
# Create a list list1 = ["val1", "val2", "val3"] print("list1 =", list1) # Print the element at position 1 in the list print("list1[1] =", list1[1])
Output:
list1 = ['val1', 'val2', 'val3']
list1[1] = val2
2. Iterate the list using a for
loop
In most situations you’ll probably only need to iterate over items in a single list. But it’s also possible for a list to contain other lists as its elements. This is called a nested list.
The following example shows how to iterate through and print elements from a single-level list and a nested list, using a for
loop.
# Create a list list1 = [1, 2, 3, 4, 5] print("list1 =", list1) # Loop through and print values print("Items in list1 are:") for i in list1: print(i) # Create a list of lists list_of_lists = [[2, 4, 6, 8, 10], [1, 3, 5, 7, 9]] print("\nlist_of_lists =", list_of_lists) # Loop through and print values print("Items in list_of_lists are:") for outer_list in list_of_lists: for inner_list in outer_list: print(inner_list)
Output:
list1 = [1, 2, 3, 4, 5]
Items in list1 are:
1
2
3
4
5
list_of_lists = [[2, 4, 6, 8, 10], [1, 3, 5, 7, 9]]
Items in list_of_lists are:
2
4
6
8
10
1
3
5
7
9
3. Iterate the list using a while
loop
In some situations, a for
loop won’t be suitable for the elements you need to retrieve. A while
loop can be more useful if you want to keep iterating until a pre-determined scenario takes place.
The following example shows how to iterate through a Python list and print elements using a while
loop.
# Create a list list1 = [1, 2, 3, 4, 5, 6] print("list1 =", list1) # Use a 'while' loop to print the first element, then every 2nd element in a list i = 0 while i < len(list1): print(list1[i]) i += 2
Output:
list1 = [1, 2, 3, 4, 5, 6]
1
3
5
Python List Comprehension
If you're unfamiliar with list comprehensions in Python, they can be a great way to convey complex logic in a single line, without losing sight of what the code is trying to achieve.
List comprehensions contain can contain loops and if..else conditional logic. The following code shows a simple example of how a for
loop that multiplies list elements by 2 can be rewritten as a list comprehension.
# Create a list list1 = [1, 2, 3, 4, 5] print("\n'for' loop:\nlist1 =", list1) # Use a 'for' loop to multiply each element by 2 for i in list1: list1[i-1] = i * 2 print("list1 =", list1) # Recreate our list list1 = [1, 2, 3, 4, 5] print("\nList comprehension\nlist1 =", list1) # Using list comprehension to multiply each element by 2 list1 = [i * 2 for i in list1] print("list1 after comprehension =", list1)
Output:
'for' loop:
list1 = [1, 2, 3, 4, 5]
list1 = [2, 4, 6, 8, 10]
List comprehension
list1 = [1, 2, 3, 4, 5]
list1 after comprehension = [2, 4, 6, 8, 10]
Example 2: Using if..else in list comprehension
# Create a list list1 = [1, 2, 3, 4, 5] print("list1 =", list1) # Using list comprehension to multiply odd numbers by 2 list1 = [i * 2 if i%2 != 0 else i for i in list1] print("list1 after comprehension =", list1)
Output:
list1 = [1, 2, 3, 4, 5]
list1 after comprehension = [2, 2, 6, 4, 10]
Example 3: Filtering a list using list comprehension
# Create a list list1 = [1, 2, 3, 4, 5] print("list1 =", list1) # Using list comprehension to filter list1 down to only even numbers list1 = [i for i in list1 if i%2 == 0] print("list1 after comprehension =", list1)
Output:
list1 = [1, 2, 3, 4, 5]
list1 after comprehension = [2, 4]
So, why use a list comprehension?
Being able to use fewer lines of code can make it easier to read, but there's also a performance benefit. With list comprehensions, Python allocates the list's memory first, before adding the elements to it. This is compared to the for
loop, which resizes the list at runtime.
Comprehensions also avoid making calls to append()
, which can also provide a minor speed increase.
Update a List
The easiest way to update an item or series of items in a Python list is by assigning a new value to the index of the item(s).
The most efficient way of doing this if you know the index of the item is list[index] = value
. If you don't know the item's index in the list, find the index using index(value)
then apply the same: list[index(value)] = new_value
.
# Create a list list1 = [1, 2, 3, 4, 5] print("list1 =", list1) # Set the first item to be a 6 instead of a 1 list1[0] = 6 print("list1 after update =", list1)
Output:
list1 = [1, 2, 3, 4, 5]
list1 after update = [6, 2, 3, 4, 5]
Example 2a: If you don't know the item's index (poor performance):
# Create a list list1 = [1, 2, 3, 4, 5] print("list1 =", list1) # Find the index of 5, then overwrite value with 6 for idx, item in enumerate(list1): if item == 5: list1[idx] = 6 print("list1 after 'for' loop update =", list1)
Output:
list1 = [1, 2, 3, 4, 5]
list1 after 'for' loop update = [1, 2, 3, 4, 6]
Example 2b: If you don't know the item's index (good performance):
# Create a list list1 = [1, 2, 3, 4, 5] print("list1 =", list1) # Find value 4 in list1 and update to be 7 using index() list1[list1.index(4)] = 7 print("list1 after index() update=", list1)
Output:
list1 = [1, 2, 3, 4, 5]
list1 after index() update= [1, 2, 3, 7, 5]
Example 2c: If you don't know the item's index (optimal performance):
# Create a list list1 = [1, 2, 3, 4, 5] print("list1 =", list1) # Find value 4 in list1 and update to be 7 using list comprehension list1 = [7 if x==4 else x for x in list1] print("list1 after list comprehension update=", list1)
Output:
list1 = [1, 2, 3, 4, 5]
list1 after list comprehension update= [1, 2, 3, 7, 5]
Example 3: If you want to overwrite a series of items (slice assignment):
# Create a list list1 = [1, 2, 3, 4, 5] print("list1 =", list1) # Replace the first 2 values with [7, 8] list1[0:2] = [7, 8] print("list1 after slice update=", list1)
Output:
list1 = [1, 2, 3, 4, 5]
list1 after slice update= [7, 8, 3, 4, 5]
In example 3, slice assignment is used to replace the slice of [0:2]
with the contents of [7, 8]
.
Delete from a List
Python has 4 main techniques for deleting items from a list, or deleting the list object entirely. These are:
- The
del
keyword - The
pop()
- The
remove()
method - The
clear()
method
The del
keyword removes the item at a specific index. You can also use del
to remove values from a range of indexes, using slicing.
If you want to delete an entire list in Python, you can apply the del
keyword to the list object, without specifying a slice or index.
# Create a list list1 = [1, 2, 3, 4, 5] print("list1 =", list1) # Use 'del' to remove the value at index 3 del list1[3] print("After 'del list1[3]' =", list1) # Now use 'del' to remove all values from index 2 onwards del list1[2:] print("After 'del list1[2:]' =", list1) # Now use 'del' to remove the list1 object del (list1) print("After 'del (list1)' =", list1)
Output:
list1 = [1, 2, 3, 4, 5]
After 'del list1[3]' = [1, 2, 3, 5]
After 'del list1[2:]' = [1, 2]
Traceback (most recent call last):
File "", line 14, in
print("After 'del (list1)' =", list1)
NameError: name 'list1' is not defined
Notice how we get a NameError when trying to print list1
in the final line of the code. That's because the object no longer exists after executing del (list1)
.
The pop()
method will remove an item from the list at a specific index and return the value. Throws a IndexError
if the index passed to pop()
is not in range.
Syntax: list.pop(index)
# Create a list list1 = [1, 2, 3, 4, 5] print("list1 =", list1) # Example 1: Use pop() without specifying index. Removes last element print("Removed value: ", list1.pop()) print("After 'list1.pop()': ", list1) # Example 2: Pop last element using negative index print("\nRemoved value: ", list1.pop(-1)) print("After 'list1.pop(-1)': ", list1) # Example 3: Pop specific element using positive index print("\nReturn Value: ", list1.pop(2)) print("After 'list1.pop(2)': ", list1) # Example 4: Attempt to pop() index that isn't in list list1.pop(10)
Output:
list1 = [1, 2, 3, 4, 5]
Removed value: 5
After 'list1.pop()': [1, 2, 3, 4]
Removed value: 4
After 'list1.pop(-1)': [1, 2, 3]
Return Value: 3
After 'list1.pop(2)': [1, 2]
Traceback (most recent call last):
File "", line 17, in
list1.pop(10)
IndexError: pop index out of range
3. Using the remove() method
Using remove()
will remove the first matching element in the list. Throws a ValueError
if the element passed to the method doesn't exist in the list.
The remove()
method is the only form of deletion in Python lists that has to search the whole object.
Syntax: list.remove(element)
# Create a list list1 = [1, 2, 2, 3, 4, 5] print("list1 =", list1) # Example 1: Remove 5 from the list list1.remove(5) print("After 'list1.remove(5)' =", list1) # Example 2: Remove 2 from the list (duplicate element) list1.remove(2) print("After 'list1.remove(2)' =", list1) # Example 3: Attempt to remove element that's not in list list1.remove(9)
Output:
list1 = [1, 2, 2, 3, 4, 5]
After 'list1.remove(5)' = [1, 2, 2, 3, 4]
After 'list1.remove(2)' = [1, 2, 3, 4]
Traceback (most recent call last):
File "", line 13, in
list1.remove(9)
ValueError: list.remove(x): x not in list
4. Using the clear() method
The clear()
method removes all items from a Python list, but doesn't remove the list object. To remove the list object, you can call del (list)
.
If you wanted to use del
to remove all items from a list instead of clear()
, you could do so using del [:]
.
Syntax: list.clear()
# Create a list list1 = [1, 2, 3, 4, 5] print("list1 =", list1) # Use clear() to empty list1 list1.clear() print("After 'list1.clear()' =", list1)
Output:
list1 = [1, 2, 3, 4, 5]
After 'list1.clear()' = []
Slicing Python Lists
Lists in Python can be sliced to return a new object containing the indices requested in its parameters.
Syntax: list[start, stop, step]. Or: list[stop]
Despite the simple syntax, slicing lists can be incredibly powerful. Listed below are the parameter configurations for list slicing, and their expected results.
Slicing lists using positive index rangesSyntax | Returns |
---|---|
list[0] | First item in the list. |
list[:2] | First two items in the list. |
list[2:] | Everything except the first two items. |
list[3:5] | Items from index 3 to index 4, inclusive. |
list[:] | All items in the list. |
Syntax | Returns |
---|---|
list[-1] | Last item in the list. |
list[-2:] | Last two items in the list. |
list[:-2] | Everything except the last two items. |
list[::-1] | All items in the list, reversed. |
list[1::-1] | The first two items, reversed. |
list[:-3:-1] | The last two items, reversed. |
list[-3::-1] | Everything except the last two items, reversed. |
# Create a list list1 = ["v1", "v2", "v3", "v4", "v5", "v6"] print("list1 =", list1) # First item in the list print("list1[0] =", list1[0]) # First two items in the list print("list[:2] =", list1[:2]) # Everything except the first two items print("list[2:] =", list1[2:]) # Items from index 3 to index 4, inclusive print("list[3:5] =", list1[3:5]) # All items in the list print("list[:] =", list1[:])
Output:
list1 = ['v1', 'v2', 'v3', 'v4', 'v5', 'v6']
list1[0] = v1
list[:2] = ['v1', 'v2']
list[2:] = ['v3', 'v4', 'v5', 'v6']
list[3:5] = ['v4', 'v5']
list[:] = ['v1', 'v2', 'v3', 'v4', 'v5', 'v6']
Example 2: List slicing using negative index ranges
# Create a list list1 = ["v1", "v2", "v3", "v4", "v5", "v6"] print("list1 =", list1) # Last item in the list print("list1[-1] =", list1[-1]) # Last two items in the list print("list1[-2:] =", list1[-2:]) # Everything except the last two items print("list1[:-2] =", list1[:-2]) # All items in the list, reversed print("list1[::-1] =", list1[::-1]) # The first two items, reversed print("list1[1::-1] =", list1[1::-1]) # The last two items, reversed print("list1[:-3:-1] =", list1[:-3:-1]) # Everything except the last two items, reversed print("list1[-3::-1] =", list1[-3::-1])
Output:
list1 = ['v1', 'v2', 'v3', 'v4', 'v5', 'v6']
list1[-1] = v6
list1[-2:] = ['v5', 'v6']
list1[:-2] = ['v1', 'v2', 'v3', 'v4']
list1[::-1] = ['v6', 'v5', 'v4', 'v3', 'v2', 'v1']
list1[1::-1] = ['v2', 'v1']
list1[:-3:-1] = ['v6', 'v5']
list1[-3::-1] = ['v4', 'v3', 'v2', 'v1']
Testing List Membership
Using in
and not in
can determine whether or not a list contains a specific value.
# Create a test list list1 = [1, 2, 3, 4] print("list1 =", list1) # Use in to check if list1 contains 1 (TRUE) print("1 in list1 =", 1 in list1) # Use in to check if list1 contains 5 (FALSE) print("5 in list1 =", 5 in list1) # Use not in to check if list1 contains 5 (TRUE) print("5 not in list1 =", 5 not in list1) # Use not in to check if list1 contains 1 (FALSE) print("1 not in list1 =", 1 not in list1)
Output:
list1 = [1, 2, 3, 4]
1 in list1 = True
5 in list1 = False
5 not in list1 = True
1 not in list1 = False
It's also possible to use membership logic (in
and not in
) to filter down the values you want to work with.
In the example below, we create a list of lists, then only print the inner lists that contain the value '6'.
# Create a list of lists list1 = [] list1.append([1, 2, 3, 4]) list1.append([3, 4, 5, 6]) list1.append([3, 4, 5, 8]) list1.append([5, 6, 7, 8]) # Print lists that contain 3 for numbers in list1: if 3 in numbers: print("list contains 3: ", numbers)
Output:
list contains 3: [1, 2, 3, 4]
list contains 3: [3, 4, 5, 6]
list contains 3: [3, 4, 5, 8]
List Operators
Python only supports the +
operator for use with lists. This means you can concatenate 2 or more lists together, but cannot subtract one from the other using the -
operator. Attempting to do so will result in a TypeError
.
# Create two lists list1 = [1, 2, 3, 4, 5] list2 = [6, 7, 8, 9, 10] print("list1 =", list1) print("list2 =", list2) # Add the two lists together using + operator list3 = list1 + list2 print("list1 + list2 =", list3) # Attempt to subtract list2 from list3 using the - operator list3 = list3 - list2 # Same as: list3 -= list2 print("list3 - list2 =", list3)
Output:
list1 = [1, 2, 3, 4, 5]
list2 = [6, 7, 8, 9, 10]
list1 + list2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Traceback (most recent call last):
File "", line 11, in
list3 = list3 - list2 # Same as: list3 -= list2
TypeError: unsupported operand type(s) for -: 'list' and 'list'
Built-in Functions
Python lists can be used with a variety of in-built functions. This includes len()
, min()
, max()
and sorted()
.
The built-in len()
function returns the total number of items in the given list.
Syntax: len(list)
# Creat a list list1 = [1, 2, 3, 4, 5] print("list1 =", list1) # Print the length of the list print("len(list1) =", len(list1))
Output:
list1 = [1, 2, 3, 4, 5]
len(list1) = 5
min()
The min()
function returns the smallest element in the list. If the list contains strings, the strings are compared lexicographically. If the list contains a combination of strings and numeric types, a TypeError will be thrown.
# Create a list of integers list1 = [1, 2, 3, 4, 5] print("list1 =", list1) # Print the min() of the list print("min(list1) =", min(list1)) # Create a list of strings list2 = ["feg", "abc", "aaa", "tyu", "zzz"] print("\nlist2 =", list2) # Print the min() of the list print("min(list2) =", min(list2)) # Create a list of both integers and strings list3 = [1, "abc", 2, "tyu", "zzz"] print("\nlist3 =", list3) # Print the min() of the list print("min(list3) =", min(list3))
Output:
list1 = [1, 2, 3, 4, 5]
min(list1) = 1
list2 = ['feg', 'abc', 'aaa', 'tyu', 'zzz']
min(list2) = aaa
list3 = [1, 'abc', 2, 'tyu', 'zzz']
Traceback (most recent call last):
File "", line 19, in
print("min(list3) =", min(list3))
TypeError: '<' not supported between instances of 'str' and 'int'
max()
The max()
function returns the largest element in the list. If the list contains strings, the strings are compared lexicographically. If the list contains a combination of strings and numeric types, a TypeError will be thrown.
# Create a list of integers list1 = [1, 2, 3, 4, 5] print("list1 =", list1) # Print the max() of the list print("max(list1) =", max(list1)) # Create a list of strings list2 = ["feg", "abc", "aaa", "tyu", "zzz"] print("\nlist2 =", list2) # Print the max() of the list print("max(list2) =", max(list2)) # Create a list of both integers and strings list3 = [1, "abc", 2, "tyu", "zzz"] print("\nlist3 =", list3) # Print the max() of the list print("max(list3) =", max(list3))
Output:
list1 = [1, 2, 3, 4, 5]
max(list1) = 5
list2 = ['feg', 'abc', 'aaa', 'tyu', 'zzz']
max(list2) = zzz
list3 = [1, 'abc', 2, 'tyu', 'zzz']
Traceback (most recent call last):
File "", line 19, in
print("max(list3) =", max(list3))
TypeError: '>' not supported between instances of 'str' and 'int'
sorted()
The sorted()
function can be called on an existing list to return a new, sorted version of the list.
This is in contrast to the list.sort()
method, which sorts the list in place, without creating a new object.
# Create a list list1 = [1, 2, 3, 6, 8, 3, 4] print("list1 =", list1) # Sort the list using sorted() print("sorted(list1) =", sorted(list1)) # Check list1 has remained in the original order print("list1 =", list1)
Output:
list1 = [1, 2, 3, 6, 8, 3, 4]
sorted(list1) = [1, 2, 3, 3, 4, 6, 8]
list1 = [1, 2, 3, 6, 8, 3, 4]
It's also possible to reverse the order of a list, using sorted(list, reverse=True)
.
# Create a list list1 = [1, 2, 3, 6, 8, 3, 4] print("list1 =", list1) # Sort the list in reverse order using sorted(list1, reverse=True) print("sorted(list1, reverse=True) =", sorted(list1, reverse=True))
Output:
list1 = [1, 2, 3, 6, 8, 3, 4]
sorted(list1, reverse=True) = [8, 6, 4, 3, 3, 2, 1]
List Methods
Python has a wide range of useful methods that can be used with list objects. This section of the Python lists guide will walk you through each method in detail, complete with clear, annotated code samples.
Method | Description |
---|---|
append() | Adds a single element to the list. |
clear() | Removes all items from a list. |
copy() | Returns a shallow copy of the list. |
count() | Returns the number of occurrences of a specified element in the list. |
extend() | Add multiple elements from one list to another list. |
index() | Returns the index of the first occurrence of a specified value. |
insert() | Adds an element to the list at the specified position. |
pop() | Remove an element at the given index. |
remove() | Removes the first occurrence of a specified value from the list. |
reverse() | Reverses the elements in a list. |
sort() | Sorts the contents of a list in place, without creating a new list. |
The append()
method is used to add a single element to the list.
# Create a list list1 = [1, 2, 3, 4, 5] print("list1 =", list1) # Call append() to add 6 to the list list1.append(6) print("After append(6), list1 =", list1)
Output:
list1 = [1, 2, 3, 4, 5]
After append(6), list1 = [1, 2, 3, 4, 5, 6]
clear()
The clear()
method removes all items from a list.
# Create a list list1 = [1, 2, 3, 4, 5] print("list1 =", list1) # Call clear() to remove all elements from list1 list1.clear() print("After clear(), list1 =", list1)
Output:
list1 = [1, 2, 3, 4, 5]
After clear(), list1 = []
copy()
The copy()
method returns a shallow copy of the list.
# Create a list list1 = [1, 2, 3, 4, 5] print("list1 =", list1) # Call copy() to create a shallow copy of list1 list2 = list1.copy() print("After copy(), list2 =", list2)
Output:
list1 = [1, 2, 3, 4, 5]
After copy(), list2 = [1, 2, 3, 4, 5]
count()
The count()
method returns the number of occurrences of a specified element in the list.
# Create a list list1 = [1, 2, 3, 3, 3, 3, 4, 5] print("list1 =", list1) # Call count() to count occurences of 3 print("count(3) =", list1.count(3))
Output:
list1 = [1, 2, 3, 3, 3, 3, 4, 5]
count(3) = 4
extend()
The extend()
method allows you to add multiple elements from a list to another list.
# Create two lists list1 = [1, 2, 3, 4, 5] list2 = [5, 6, 7, 8] print("list1 =", list1) print("list2 =", list2) # Call extend() to add elements from list2 to list1 list1.extend(list2) print("After extend(list2), list1 =", list1)
Output:
list1 = [1, 2, 3, 4, 5]
list2 = [5, 6, 7, 8]
After extend(list2), list1 = [1, 2, 3, 4, 5, 5, 6, 7, 8]
index()
The index()
method returns the index of the first occurrence of a specified value.
# Create a list list1 = [1, 2, 3, 3, 3, 3, 4, 5] print("list1 =", list1) # Call index() to return first occurence of 3 print("index(3) =", list1.index(3))
Output:
list1 = [1, 2, 3, 3, 3, 3, 4, 5]
index(3) = 2
insert()
The insert()
method adds elements to the list at the specified position.
# Create a list list1 = [1, 2, 3, 4, 5] print("list1 =", list1) # At position 2, insert 3 list1.insert(2,3) print("After insert(2,3) =", list1)
Output:
list1 = [1, 2, 3, 4, 5]
After insert(2,3) = [1, 2, 3, 3, 4, 5]
pop()
The pop()
method is used to remove an element at the given index. Defaults to the last item in the list if no index is specified. Returns the item removed.
# Create a list list1 = [1, 2, 3, 4, 5] print("list1 =", list1) # Use pop() to remove last item by default print("list1.pop() =", list1.pop()) print("After pop() =", list1) # Use pop() to remove the item at position 2 print("list1.pop(2) =", list1.pop(2)) print("After pop(2) =", list1)
Output:
list1 = [1, 2, 3, 4, 5]
list1.pop() = 5
After pop() = [1, 2, 3, 4]
list1.pop(2) = 3
After pop(2) = [1, 2, 4]
remove()
The remove()
method removes the first occurrence of a specified value from the list.
# Create a list list1 = [1, 2, 3, 3, 4, 5] print("list1 =", list1) # Remove the first item with value 3 list1.remove(3) print("After remove(3) =", list1)
Output:
list1 = [1, 2, 3, 3, 4, 5]
After remove(3) = [1, 2, 3, 4, 5]
reverse()
The reverse()
method reverses the elements in a list. Returns None
.
# Create a list list1 = [1, 2, 3, 3, 4, 5] print("list1 =", list1) # Reverse list1 list1.reverse() print("After list1.reverse() =", list1)
Output:
list1 = [1, 2, 3, 3, 4, 5]
After list1.reverse() = [5, 4, 3, 3, 2, 1]
sort()
The sort()
method sorts the contents of a list. This works on the object that it's called upon, rather than creating a new object, which is why print(list1.sort())
returns none
.
If you do want a new list returned with the sorted contents, rather than mutating the existing list, you can use the built-in function sorted()
.
# Create a list list1 = [1, 2, 6, 4, 9, 3, 5, 2] print("list1 =", list1) # Sort and print list1 list1.sort() print("list1.sort() =", list1) # Sort list1 in reverse order list1.sort(reverse=True) print("list1.sort(reverse=True) =", list1) # Create a new sorted list using the sorted() built-in function print("sorted(list1) =", sorted(list1)) print("list1 retains its order: ", list1)
Output:
list1 = [1, 2, 6, 4, 9, 3, 5, 2]
list1.sort() = [1, 2, 2, 3, 4, 5, 6, 9]
list1.sort(reverse=True) = [9, 6, 5, 4, 3, 2, 2, 1]
sorted(list1) = [1, 2, 2, 3, 4, 5, 6, 9]
list1 retains its order: [9, 6, 5, 4, 3, 2, 2, 1]
Assignment also makes it possible to sort multiple lists at the same time. In the example below, even though we apply sort()
to list2
, it also sorts list1
.
# Create a list list1 = [6,1,3,4,2,5] print("list1 =", list1) # Assign list1 to new variable list2 list2 = list1 # Sort list2 and prove it also sorts list1 list2.sort() print("list2.sort() =", list2) print("list1 =", list1)
Output:
list1 = [6, 1, 3, 4, 2, 5]
list2.sort() = [1, 2, 3, 4, 5, 6]
list1 = [1, 2, 3, 4, 5, 6]
List Equality
If two lists have the same contents in the same order, they are considered equal (set1 == set2 returns true). If the sets contain the same items but in different orders, set1 == set returns false.
List of Lists
There are some cases where you will need to create a list of lists. This is where a list contains other lists as its elements.
# Create two list list1 = [1, 2, 3, 4] list2 = [5, 6, 7, 8] print("list1 =", list1) print("list2 =", list2) # Create list3, which contains list1 and list2 as its elements list3 = [list1, list2] print("[list1, list2] =", list3)
Output:
list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8]
[list1, list2] = [[1, 2, 3, 4], [5, 6, 7, 8]]