Cheat Sheet Python Lists

journey into python

This cheat sheet python lists comes from the Python Lists learning post. You can also check out Python.org for more information on lists. Cheat Sheet Python Lists is one of many cheat sheets that we are creating to help everyone out. It’s for those that always forget the small things(like me).

Lists are mutable, storing multiple elements in a single variable. Lists are one of 4 built-in data types in Python used to store collections of data.

Syntax

list = ["element","ect..."]

Common Mistakes

Not initializing an empty list before manipulating elements within a list.

Syntax for list missing or misplaced. ["",""]

Trying to index an element that is not in the list.

Method Description
list[i] = x Replaces the element at index i with x
list.append(x) Inserts x at the end of the list
list.insert(i, x) Inserts x at index i
list.pop(i) Returns the element a index i, also removing it from the list. If i is omitted, the last element is returned and removed.
list.remove(x) Removes the first occurrence of x in the list
list.sort() Sorts the items in the list
list.reverse() Reverses the order of items of the list
list.clear() Removes all the items of the list
list.copy() Creates a copy of the list
list.extend(other_list) Appends all the elements of other_list at the end of list

List comprehension

[expression for variable in list] Creates a new list based on the given list. Each element is the result of the given expression.

[expression for variable in list if condition] Creates a new list based on the given list. Each element is the result of the given expression; elements only get added if the condition is true.