Python3 Cheatsheet
Comments
Arithmetic Operations
+
for addition-
for subtraction*
for multiplication/
for division%
for modulus (returns the remainder)**
for exponentiation
Plus-Equals Operator +=
+=
Variables
Modulo Operator %
%
The result of the expression
4 % 2
would result in the value 0, because 4 is evenly divisible by 2 leaving no remainder.The result of the expression
7 % 3
would return 1, because 7 is not evenly divisible by 3, leaving a remainder of 1.
A modulo calculation returns the remainder of a division between the first and second number. For example:
Integers
String Concatenation
Strings
Floating Point Numbers
print()
Function
print()
Functionelif Statements
or Operator
The Python
or
operator combines two Boolean expressions and evaluates toTrue
if at least one of the expressions returnsTrue
. Otherwise, if both expressions areFalse
, then the entire expression evaluates toFalse
.
Equal Operator ==
==
Not Equals Operator !=
!=
Comparison Operators
if Statements
else Statements
and Operator
not Operator
Lists
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 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 plus symbol +
. As shown in the code block, this will result in a new list containing the same items in the same order with the first list’s items coming first.
Note: This will not work for adding one item at a time (use .append()
method). In order to add one item, 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 multiple different data types within the same square brackets. The possible data types within a list include numbers, strings, other objects, and even other lists.
List Method .append()
.append()
In Python, you can add values to the end of a list using the .append()
method. This will place the object passed in as a new element at the very end of the list.
Zero-Indexing
In Python, list index begins at zero and ends at the length of the list minus one. For example, in this list, 'Andy'
is found at index 2
.
List Indices
To access a list element by index, square bracket notation is used: list[index]
.
Negative List Indices
To select the last element,
my_list[-1]
.To select the last three elements,
my_list[-3:]
.To select everything except the last two elements,
my_list[:-2]
.
Modifying 2D Lists
In order to modify elements in a 2D list, an index for the sublist and the index for the element of the sublist need to be provided. The format for this is list[sublist_index][element_in_sublist_index] = new_value
.
Accessing 2D Lists
In order to access elements in a 2D list, an index for the sublist and the index for the element of the sublist both need to be provided. The format for this is list[sublist_index][element_in_sublist_index]
.
List Method .remove()
.remove()
The .remove()
method in Python is used to remove an element from a list by passing in the value of the element to be removed as an argument. In the case where two or more elements in the list have the same value, the first occurrence of the element is removed.
List Method .count()
.count()
The .count()
Python list method searches a list for whatever search term it receives as an argument, then returns the number of matching entries found.
Determining List Length with len()
len()
The Python len()
function can be used to determine the number of items found in the list it accepts as an argument.
List Method .sort()
.sort()
The .sort()
Python list method will sort the contents of whatever list it is called on. Numerical lists will be sorted in ascending order, and lists of Strings will be sorted into alphabetical order. It modifies the original list, and has no return value.
List Slicing
A slice, or sub-list of Python list elements can be selected from a list using a colon-separated starting and ending point.
The syntax pattern is myList[START_NUMBER:END_NUMBER]
. The slice will include the START_NUMBER
index, and everything until but excluding the END_NUMBER
item.
When slicing a list, a new list is returned, so if the slice is saved and then altered, the original list remains the same.
sorted()
Function
sorted()
FunctionThe Python sorted()
function accepts a list as an argument, and will return a new, sorted list containing the same elements as the original. Numerical lists will be sorted in ascending order, and lists of Strings will be sorted into alphabetical order. It does not modify the original, unsorted list.
List Method .insert()
.insert()
The Python list method .insert()
allows us to add an element to a specific index in a list.
It takes in two inputs:
The index that you want to insert into.
The element that you want to insert at the specified index.
List Method .pop()
.pop()
The .pop()
method allows us to remove an element from a list while also returning it. It accepts one optional input which is the index of the element to remove. If no index is provided, then the last element in the list will be removed and returned.
break
Keyword
break
KeywordIn a loop, the break
keyword escapes the loop, regardless of the iteration number. Once break
executes, the program will continue to execute after the loop.
In this example, the output would be:
0
254
2
Negative number detected!
Python List Comprehension
Python list comprehensions provide a concise way for creating lists. It consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses: [EXPRESSION for ITEM in LIST <if CONDITIONAL>]
.
The expressions can be anything - any kind of object can go into a list.
A list comprehension always returns a list.
Python For Loop
When writing a for
loop, remember to properly indent each action, otherwise an IndentationError
will result.
The Python continue
Keyword
continue
KeywordIn Python, the continue
keyword is used inside a loop to skip the remaining code inside the loop code block and begin the next loop iteration.
Python Loops with range()
.
range()
.In Python, a for
loop can be used to perform an action a specific number of times in a row.
The range()
function can be used to create a list that can be used to specify the number of iterations in a for
loop.
Infinite Loop
An infinite loop is a loop that never terminates. Infinite loops result when the conditions of the loop prevent it from terminating.
Python while
Loops
while
LoopsIn Python, a while
loop will repeatedly execute a code block as long as a condition evaluates to True
.
The condition of a while
loop is always checked first before the block of code runs. If the condition is not met initially, then the code block will never run.
Python Nested Loops
In Python, loops can be nested inside other loops. Nested loops can be used to access items of lists which are inside other lists. The item selected from the outer loop can be used as the list for the inner loop to iterate over.
Last updated