Learn Python 3 - Lists Cheatsheet - Codecademy
Learn Python 3 - Lists Cheatsheet - Codecademy
Lists
Lists
In Python, lists are ordered collections of items that allow for easy use of a set of data. primes = [2, 3, 5, 7, 11]
List values are placed in between square brackets [ ] , separated by commas. It is
print(primes)
good practice to put a space between the comma and the next value. The values in a
list do not need to be unique (the same value can be repeated).
Empty lists do not contain any values within the square brackets. empty_list = []
In Python, lists can be added to each other using the plus symbol + . As shown in the items = ['cake', 'cookie', 'bread']
code block, this will result in a new list containing the same items in the same order
total_items = items + ['biscuit', 'tart']
with the first list’s items coming first.
Note: This will not work for adding one item at a time (use .append() method). In print(total_items)
order to add one item, create a new list with a single value and then use the plus # Result: ['cake', 'cookie', 'bread', 'biscuit', 'tart']
symbol to add the list.
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-lists/cheatsheet 1/9
09/12/2023, 08:08 Learn Python 3: Lists Cheatsheet | Codecademy
In Python, lists are a versatile data type that can contain multiple different data types numbers = [1, 2, 3, 4, 10]
within the same square brackets. The possible data types within a list include numbers,
names = ['Jenny', 'Sam', 'Alexis']
strings, other objects, and even other lists.
mixed = ['Jenny', 1, 2]
list_of_lists = [['a', 1], ['b', 2]]
In Python, you can add values to the end of a list using the .append() method. This orders = ['daisies', 'periwinkle']
will place the object passed in as a new element at the very end of the list. Printing the
orders.append('tulips')
list afterwards will visually show the appended value. This .append() method is not to
be confused with returning an entirely new list with the passed object. print(orders)
# Result: ['daisies', 'periwinkle', 'tulips']
Zero-Indexing
In Python, list index begins at zero and ends at the length of the list minus one. For names = ['Roger', 'Rafael', 'Andy', 'Novak']
example, in this list, 'Andy' is found at index 2 .
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-lists/cheatsheet 2/9
09/12/2023, 08:08 Learn Python 3: Lists Cheatsheet | Codecademy
List Indices
Python list elements are ordered by index, a number referring to their placement in the berries = ["blueberry", "cranberry", "raspberry"]
list. List indices start at 0 and increment by one.
To access a list element by index, square bracket notation is used: list[index] .
berries[0] # "blueberry"
berries[2] # "raspberry"
Negative indices for lists in Python can be used to reference elements in relation to the soups = ['minestrone', 'lentil', 'pho', 'laksa']
end of a list. This can be used to access single list elements or as part of defining a list
soups[-1] # 'laksa'
range. For instance:
To select the last element, my_list[-1] . soups[-3:] # 'lentil', 'pho', 'laksa'
To select the last three elements, my_list[-3:] . soups[:-2] # 'minestrone', 'lentil'
To select everything except the last two elements, my_list[:-2] .
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-lists/cheatsheet 3/9
09/12/2023, 08:08 Learn Python 3: Lists Cheatsheet | Codecademy
Modifying 2D Lists
In order to modify elements in a 2D list, an index for the sublist and the index for the # A 2D list of names and hobbies
element of the sublist need to be provided. The format for this is list[sublist_index]
class_name_hobbies = [["Jenny", "Breakdancing"], ["Alexus",
[element_in_sublist_index] = new_value .
"Photography"], ["Grace", "Soccer"]]
# Output
# [["Jenny", "Meditation"], ["Alexus", "Photography"],
["Grace", "Soccer"]]
Accessing 2D Lists
In order to access elements in a 2D list, an index for the sublist and the index for the # 2D list of people's heights
element of the sublist both need to be provided. The format for this is
heights = [["Noelle", 61], ["Ali", 70], ["Sam", 67]]
list[sublist_index][element_in_sublist_index] .
# Access the sublist at index 0, and then access the 1st
index of that sublist.
noelles_height = heights[0][1]
print(noelles_height)
# Output
# 61
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-lists/cheatsheet 4/9
09/12/2023, 08:08 Learn Python 3: Lists Cheatsheet | Codecademy
The .remove() method in Python is used to remove an element from a list by passing # Create a list
in the value of the element to be removed as an argument. In the case where two or
shopping_line = ["Cole", "Kip", "Chris", "Sylvana", "Chris"]
more elements in the list have the same value, the first occurrence of the element is
removed.
# Removes the first occurance of "Chris"
shopping_line.remove("Chris")
print(shopping_line)
# Output
# ["Cole", "Kip", "Sylvana", "Chris"]
The .count() Python list method searches a list for whatever search term it receives backpack = ['pencil', 'pen', 'notebook', 'textbook', 'pen',
as an argument, then returns the number of matching entries found.
'highlighter', 'pen']
numPen = backpack.count('pen')
print(numPen)
# Output: 3
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-lists/cheatsheet 5/9
09/12/2023, 08:08 Learn Python 3: Lists Cheatsheet | Codecademy
The Python len() function can be used to determine the number of items found in knapsack = [2, 4, 3, 7, 10]
the list it accepts as an argument.
size = len(knapsack)
print(size)
# Output: 5
The .sort() Python list method will sort the contents of whatever list it is called on. exampleList = [4, 2, 1, 3]
Numerical lists will be sorted in ascending order, and lists of Strings will be sorted into
exampleList.sort()
alphabetical order. It modifies the original list, and has no return value.
print(exampleList)
# Output: [1, 2, 3, 4]
List Slicing
A slice, or sub-list of Python list elements can be selected from a list using a colon- tools = ['pen', 'hammer', 'lever']
separated starting and ending point.
tools_slice = tools[1:3] # ['hammer', 'lever']
The syntax pattern is myList[START_NUMBER:END_NUMBER] . The slice will
include the START_NUMBER index, and everything until but excluding the tools_slice[0] = 'nail'
END_NUMBER item.
When slicing a list, a new list is returned, so if the slice is saved and then altered, the
# Original list is unaltered:
original list remains the same.
print(tools) # ['pen', 'hammer', 'lever']
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-lists/cheatsheet 6/9
09/12/2023, 08:08 Learn Python 3: Lists Cheatsheet | Codecademy
sorted() Function
The Python sorted() function accepts a list as an argument, and will return a new, unsortedList = [4, 2, 1, 3]
sorted list containing the same elements as the original. Numerical lists will be sorted in
sortedList = sorted(unsortedList)
ascending order, and lists of Strings will be sorted into alphabetical order. It does not
modify the original, unsorted list. print(sortedList)
# Output: [1, 2, 3, 4]
The Python list method .insert() allows us to add an element to a specific index in a # Here is a list representing a line of people at a store
list.
store_line = ["Karla", "Maxium", "Martim", "Isabella"]
It takes in two inputs:
The index that you want to insert into.
The element that you want to insert at the specified index. # Here is how to insert "Vikor" after "Maxium" and before
"Martim"
store_line.insert(2, "Vikor")
print(store_line)
# Output: ['Karla', 'Maxium', 'Vikor', 'Martim', 'Isabella']
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-lists/cheatsheet 7/9
09/12/2023, 08:08 Learn Python 3: Lists Cheatsheet | Codecademy
The .pop() method allows us to remove an element from a list while also returning it. cs_topics = ["Python", "Data Structures", "Balloon Making",
It accepts one optional input which is the index of the element to remove. If no index is
"Algorithms", "Clowns 101"]
provided, then the last element in the list will be removed and returned.
print(cs_topics)
print(removed_element)
# Output:
# ['Python', 'Data Structures', 'Balloon Making',
'Algorithms']
# 'Clowns 101'
# Output:
# ['Python', 'Data Structures', 'Algorithms']
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-lists/cheatsheet 8/9
09/12/2023, 08:08 Learn Python 3: Lists Cheatsheet | Codecademy
Print Share
https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-lists/cheatsheet 9/9