0% found this document useful (0 votes)
5 views7 pages

Learn Python 3_ Lists Cheatsheet _ Codecademy

This document is a cheatsheet for Python 3 lists, covering key concepts such as list creation, methods for adding and removing elements, and accessing elements using indices. It explains how to manipulate both 1D and 2D lists, as well as the differences between lists and tuples. Additionally, it provides examples of various list methods like .append(), .remove(), .sort(), and .pop().

Uploaded by

sohaibade
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views7 pages

Learn Python 3_ Lists Cheatsheet _ Codecademy

This document is a cheatsheet for Python 3 lists, covering key concepts such as list creation, methods for adding and removing elements, and accessing elements using indices. It explains how to manipulate both 1D and 2D lists, as well as the differences between lists and tuples. Additionally, it provides examples of various list methods like .append(), .remove(), .sort(), and .pop().

Uploaded by

sohaibade
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

9/29/24, 1:06 AM Learn Python 3: Lists Cheatsheet | Codecademy

Cheatsheets / Learn Python 3

Lists

Lists

In Python, lists are ordered collections of items that primes = [2, 3, 5, 7, 11]
allow for easy use of a set of data.
print(primes)
List values are placed in between square brackets [ ] ,
separated by commas. It is good practice to put a space
between the comma and the next value. The values in a empty_list = []
list do not need to be unique (the same value can be
repeated).
Empty lists do not contain any values within the square
brackets.

Adding Lists Together

In Python, lists can be added to each other using the items = ['cake', 'cookie', 'bread']
plus symbol + . As shown in the code block, this will
total_items = items + ['biscuit', 'tart']
result in a new list containing the same items in the
same order with the first list’s items coming first. print(total_items)
Note: This will not work for adding one item at a time # Result: ['cake', 'cookie', 'bread',
(use .append() method). In order to add one item,
'biscuit', 'tart']
create a new list with a single value and then use the
plus symbol to add the list.

Python Lists: Data Types

In Python, lists are a versatile data type that can contain numbers = [1, 2, 3, 4, 10]
multiple different data types within the same square
names = ['Jenny', 'Sam', 'Alexis']
brackets. The possible data types within a list include
numbers, strings, other objects, and even other lists. mixed = ['Jenny', 1, 2]
list_of_lists = [['a', 1], ['b', 2]]

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-lists/cheatsheet 1/7
9/29/24, 1:06 AM Learn Python 3: Lists Cheatsheet | Codecademy

List Method .append()

In Python, you can add values to the end of a list using orders = ['daisies', 'periwinkle']
the .append() method. This will place the object
orders.append('tulips')
passed in as a new element at the very end of the list.
Printing the list afterwards will visually show the print(orders)
appended value. This .append() method is not to be # Result: ['daisies', 'periwinkle',
confused with returning an entirely new list with the
'tulips']
passed object.

Zero-Indexing

In Python, list index begins at zero and ends at the names = ['Roger', 'Rafael', 'Andy',
length of the list minus one. For example, in this list,
'Novak']
'Andy' is found at index 2 .

List Indices

Python list elements are ordered by index, a number berries = ["blueberry", "cranberry",
referring to their placement in the list. List indices start
"raspberry"]
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 List Indices

Negative indices for lists in Python can be used to soups = ['minestrone', 'lentil', 'pho',
reference elements in relation to the end of a list. This
'laksa']
can be used to access single list elements or as part of
defining a list range. For instance: soups[-1] # 'laksa'
To select the last element, my_list[-1] . soups[-3:] # 'lentil', 'pho', 'laksa'
To select the last three elements,
soups[:-2] # 'minestrone', 'lentil'
my_list[-3:] .
To select everything except the last two
elements, my_list[:-2] .

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-lists/cheatsheet 2/7
9/29/24, 1:06 AM Learn Python 3: Lists Cheatsheet | Codecademy

Modifying 2D Lists

In order to modify elements in a 2D list, an index for the # A 2D list of names and hobbies
sublist and the index for the element of the sublist need
class_name_hobbies = [["Jenny",
to be provided. The format for this is
list[sublist_index][element_in_sublist_index] = "Breakdancing"], ["Alexus",
new_value . "Photography"], ["Grace", "Soccer"]]

# The sublist of Jenny is at index 0. The


hobby is at index 1 of the sublist.
class_name_hobbies[0][1] = "Meditation"
print(class_name_hobbies)

# Output
# [["Jenny", "Meditation"], ["Alexus",
"Photography"], ["Grace", "Soccer"]]

Accessing 2D Lists

In order to access elements in a 2D list, an index for the # 2D list of people's heights
sublist and the index for the element of the sublist both
heights = [["Noelle", 61], ["Ali", 70],
need to be provided. The format for this is
list[sublist_index][element_in_sublist_index] . ["Sam", 67]]
# 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 3/7
9/29/24, 1:06 AM Learn Python 3: Lists Cheatsheet | Codecademy

List Method .remove()

The .remove() method in Python is used to remove # Create a list


an element from a list by passing in the value of the
shopping_line = ["Cole", "Kip", "Chris",
element to be removed as an argument. In the case
where two or more elements in the list have the same "Sylvana", "Chris"]
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"]

Tuples

Tuples are one of the built-in data structures in Python. my_tuple = ('abc', 123, 'def', 456, 789,
Tuples are immutable, meaning we can’t modify a
'ghi')
tuple’s elements after creating one, and they do not
require an extra memory block like lists. Because of
this, tuples are great to work with if you are working len(my_tuple) # returns length of tuple
with data that won’t need to be changed in your code.
max(my_tuple) # returns maximum value of
Some of the built-in methods and functions to be used
with tuples are: len() , max() , min() , .index() and tuple
.count() . min(my_tuple) # returns maximum value of
tuple
my_tuple.index(123) # returns the
position of the value 123
my_tuple.count('abc') # returns the
number of occurrences of the value 'abc'

List Method .count()

The .count() Python list method searches a list for backpack = ['pencil', 'pen', 'notebook',
whatever search term it receives as an argument, then
'textbook', 'pen', 'highlighter', 'pen']
returns the number of matching entries found.
numPen = backpack.count('pen')

print(numPen)
# Output: 3

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-lists/cheatsheet 4/7
9/29/24, 1:06 AM Learn Python 3: Lists Cheatsheet | Codecademy

Determining List Length with len()

The Python len() function can be used to determine knapsack = [2, 4, 3, 7, 10]
the number of items found in the list it accepts as an
size = len(knapsack)
argument.
print(size)
# Output: 5

List Method .sort()

The .sort() Python list method will sort the contents exampleList = [4, 2, 1, 3]
of whatever list it is called on. Numerical lists will be
exampleList.sort()
sorted in ascending order, and lists of Strings will be
sorted into alphabetical order. It modifies the original print(exampleList)
list, and has no return value. # Output: [1, 2, 3, 4]

List Slicing

A slice, or sub-list of Python list elements can be tools = ['pen', 'hammer', 'lever']
selected from a list using a colon-separated starting
tools_slice = tools[1:3] # ['hammer',
and ending point.
The syntax pattern is 'lever']
myList[START_NUMBER:END_NUMBER] . The tools_slice[0] = 'nail'
slice will include the START_NUMBER index, and
everything until but excluding the END_NUMBER
item. # Original list is unaltered:
When slicing a list, a new list is returned, so if the slice is print(tools) # ['pen', 'hammer', 'lever']
saved and then altered, the original list remains the
same.

sorted() Function

The Python sorted() function accepts a list as an unsortedList = [4, 2, 1, 3]


argument, and will return a new, sorted list containing
sortedList = sorted(unsortedList)
the same elements as the original. Numerical lists will
be sorted in ascending order, and lists of Strings will be print(sortedList)
sorted into alphabetical order. It does not modify the # Output: [1, 2, 3, 4]
original, unsorted list.

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-lists/cheatsheet 5/7
9/29/24, 1:06 AM Learn Python 3: Lists Cheatsheet | Codecademy

List Method .insert()

The Python list method .insert() allows us to add an # Here is a list representing a line of
element to a specific index in a list.
people at a store
It takes in two inputs:
The index that you want to insert into. store_line = ["Karla", "Maxium",
The element that you want to insert at the "Martim", "Isabella"]
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']

List Method .pop()

The .pop() method allows us to remove an element cs_topics = ["Python", "Data Structures",
from a list while also returning it. It accepts one
"Balloon Making", "Algorithms", "Clowns
optional input which is the index of the element to
remove. If no index is provided, then the last element in 101"]
the list will be removed and returned.

# Pop the last element


removed_element = cs_topics.pop()

print(cs_topics)
print(removed_element)

# Output:
# ['Python', 'Data Structures', 'Balloon
Making', 'Algorithms']
# 'Clowns 101'

# Pop the element "Baloon Making"


cs_topics.pop(2)
print(cs_topics)

# Output:
# ['Python', 'Data Structures',
'Algorithms']

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-lists/cheatsheet 6/7
9/29/24, 1:06 AM Learn Python 3: Lists Cheatsheet | Codecademy

Print Share

https://www.codecademy.com/learn/learn-python-3/modules/learn-python3-lists/cheatsheet 7/7

You might also like