Python Cheat Sheet

A comprehensive list of Python concepts for the beginner.
By Ciprian Stratulat • Nov 1, 2021

 

Table of Contents

Helper functions
Comments
Docstrings
Variables
Data Types
Numbers
Integers
Floats
Operations with Numbers
Booleans
Comparisons
Strings
String Indexing
String Methods
String Formatting
Lists
List Indexing and Slicing
List Operations
Tuples
Tuple Indexing and Slicing
Tuple Operations
Dictionaries
Dictionary Operations
Dictionary Methods
Conditionals (if... elif... else)

 

Helper functions TOP

dir(...)

Show information about objects.

x = 'This is a string'
dir(x)

type(...)

Show the data type of a given object.

x = 5
type(x)

print(...)

Prints (shows on the screen) the value of the expression between the parentheses.

print('Hello world')
x = 2
print(x)

 

Comments TOP

  • special lines of code that the computer will NOT execute
  • they are meant to be read by humans only
  • useful to explain complicated logic, or provide more details or documentation
  • everything to the right of # sign is considered a comment

Single line comments

# This is a single line comment. The computer will not execute this line.
x = 45 # This is an inline comment. Only characters to the right of # sign are part of the comment.

Multi-line comments

# This is a multiline comment.
# If you need to write a comment on multiple lines, 
# you must remember to start each comment line with the # sign.

 

Docstrings TOP

  • documentation strings
  • typically used at the beginning of a function definition to explain what the function does, what inputs / outputs it has etc.

Single line docstrings

"""This is an example of a docstring. """

Multi-line docstrings

"""
This is a
multiline
docstring
"""

Docstrings in practice

def double_num(n):
	"""
	This function multiplies the given number 
         by 2 and returns the result.
	"""
	return n*2

How to programmatically access a function's docstrings

# The code below will print the documentation
# string for the doule_num function.

print(double_num.__doc__)

 

Variables TOP

  • are used to store data that needs to be accessed later
  • can be (almost) any word, except for so-caled reserved words, which are used by the Python language
    •  examples of reserved words: if, for, True, while, not, and, or, ...
  • have a name and a value
  • by convention we use all lowercase for variable names
  • by convention we use underscores to separate multiple words in a variable name (e.g. first_name)
  • variable names MUST start with a letter (not a number, etc.)
  • variables are assigned values using the = sign
  • NOTE: you can use the print built-in function to print the values of a variable to the screen
# Below, the variable count will be given the value 15.
count = 15
# Below, the variable my_count will be assigned the value 0.
my_count = 0
# Below, the variable first_name will be assigned the text 'James'
first_name = 'James'
# Below, the variable counter will be updated to be equal to 
# the old value plus 2

counter = 10
counter = counter + 2

# The variable counter is now equal to 12

 

Data Types TOP

  • data in a program can be anything: text, numbers, dates, images, binary
  • the type of data is important to know because different types have different abilities
    • e.g.: you can divide numbers, but not lines of text
  • Python has built-in support for multiple data types, which we'll discuss below

Here are some of the built-in data types:

 

Numbers TOP

  • Python has several data types for representing numbers
    • int for whole numbers (integers)
    • float for real numbers (CAUTION: when doing math with floats, you may not get very precise results!)
    • decimals also for real numbers (decimals, unlike floats, will do proper math)
# This is an integer
11
# This is a float
2.78
# The variable a is assigned the integer value 3.
a = 3
# The variable b is assigned the integer value 5.
b = 5

Below, Python will replace a with the actual value that it stores (in this case, 3), and b with the actual value that it stores (in this case, 5) and then do the math. 

a = 3
b = 5

a + b
a - b
a * b
a / b

 

Integers TOP

  • numbers without a decimal component
  • can be created from text or from other numbers
  • immutable
# Below we create an integer from the text '5'
number = int('5')
# Below we create an integer from the float number 5.67
number = int(5.67)

 

Floats TOP

  • floating-point numbers (numbers with a decimal component)
  • can be created from text or from other numbers
  • immutable
# Below we create a float from the text '5.67'
number = float('5.67')
# Below we create a float from the integer number 5
number = float(5)

The problem with floats

# The math expression below should evaluate to 0... 
# except it doesn't.

1.1 + 1.1 + 1.1 - 3.3

If you actually evaluate the code above, you will get something like 4.440892098500626e-16. Close to 0, but not quite. This is because floats are not precise. The way around this is to use the Decimal module (more on modules in a bit):

from decimal import Decimal
Decimal('1.1') + Decimal('1.1') + Decimal('1.1') - Decimal('3.3')

This will evaluate to Decimal('0.0'), which is the correct, precise result.

 

How to perform operations with numbers TOP

Python uses the following operators:

  • + for addition
  • - for subtraction
  • * for multiplication
  • / for float division (the result will be a float number)
  • // for integer division (the result will be an integer number)
  • ** for exponentiation
  • % for computing the remainder

You can combine the operators as many times as you want:

# This does a bunch of math. 
# Notice how we use a mix of integers and floats
# and a variety of operators.

((5 + 6) * 11) / 3.45) ** 3

 

ADDITION

You can add two integers. The result will be an integer.

5 + 6

You can add an integer and a float. The result will be a float.

4.1 + 6

You can add two floats. The result will be a float.

Caution: operations with floats are imprecise. See the Decimal data type for more precise operations with numbers with decimals.

1.1 + 3.5

 

SUBTRACTION

You can subtract an integer from another integer. The result will be an integer.

7 - 2

You can subtract an integer from a float (or vice-versa). The result will be a float.

9.6 - 3

You can subtract a float from another float. The result will be a float.

1.7 - 3.98

 

MULTIPLICATION

You can multiply integers. The result will be an integer.

12 * 10

You can multiply floats. The result will be a float.

1.45 * 4.32

You can multiply a float by an integer. The result will be a float.

7.3 *  5

 

DIVISION

We have two types of division: / and //

  • / returns a float (a number with decimal points)
# The code below will return 1.6666666666666667
5 / 3
  • // returns an integer result (basically it rounds the result down). We call this floor division.
# The code below returns 1
5 // 3

 

MODULO OPERATOR (%)

Use the % to get the remainder of the division.

# The code below returns 0 (4 = 2 * 2 + 0)
4 % 2

# The code below returns 1 (5 = 2 * 2 + 1)
5 % 2

 

EXPONENTIATION (x to the yth power)

Use ** to raise a number to a given power.

# The code below returns 8 (2 * 2 * 2)
2 ** 3

 

USING VARIABLES

All the operations can be performed with variables that store numbers, instead of with numbers directly. For example:

a = 2
b = 3

# The code below prints 6
print(a * b)

# The code below prints 8
print(a ** b)

# The code below prints 0
a // b

# After the code below executes, 
# variable c will store the value 14
c = (a + b) * a + 4

 

Booleans (True/False) TOP

  • boolean variables store a value of either True or False
  • they are often used when evaluating expressions to determine whether they are true or false
  • True and False are defined by the Python programming language
# The is_smaller variable below is of type bool. 
# We say that it is a boolean. In this case, it stores the 
# value True because '1 is less than 5' is a true statement.

is_smaller = 1 < 5

 

Falsy values

In addition to the boolean value False, Python evaluates the following values to False (they are equivalent to False in an if statement, for example):

  • empty lists []
  • empty tuples ()
  • empty dictionaries {}
  • empty sets set()
  • empty strings ''
  • the integer number 0
  • the floating point number 0.0
  • None
# All the examples below will print 'no'


# Example 1 - will print 'no'
if []:
    print('yes')
else:
    print('no')


# Example 2 - will print 'no'
x = 0
if x:
    print('yes')
else:
    print('no')


# Example 3 - will print 'no'
if '':
    print('yes')
else:
    print('no')


 

Truthy values

In addition to the boolean value True, Python evaluates any expression that does not have a falsy value (see above) to True. Some examples:

  • the list [1, 2, 3]
  • the list [None]
  • the list ['']
  • the tuple ('a', 'b')
  • the dictionary {'a': 1, 'b': 2}
  • the set set(5, 6)
  • the string 'hello'
  • the integer number -1
  • the floating point number 4.67
  • etc.
# All the examples below will print 'yes'


# Example 1 - will print 'yes'
if [None]:
    print('yes')
else:
    print('no')


# Example 2 - will print 'yes'
x = -1
if x:
    print('yes')
else:
    print('no')


# Example 3 - will print 'yes'
if 'hi':
    print('yes')
else:
    print('no')


 

Comparisons TOP

  • expressions that have the value of either True or False

To check for equality, use ==

# The boolean value of the expression below is True
1 == 1

# In other words, the variable c below will store the value True
c = (1 == 1)

# The boolean value of the expression below is False
1 == 5

# In other words, the variable c below will store the value False
c = (1 == 5)

 

To check for inequality, use !=

# The boolean value of the expression below is False
1 != 1

# In other words, the variable c below will store the value False
c = (1 != 1)

# The boolean value of the expression below is True
1 != 5

# In other words, the variable c below will store the value True
c = (1 != 5)

 

Other comparisons: less than <, less than or equal <=, greater than > , greater than or equal >=

# The boolean value of the expressions below is True
1 < 10
1 <= 1
1 <= 2
5 >= 3

# The boolean value of the expressions below is false
5 > 7
1 <= 0

 

You can negate comparisons using the logical operator not

# The boolean value of the expression below is False
not True

# In other words, the variable c below will store the boolean value False
c = (not True)

# The boolean value of the expression below is True
not False

# In other words, the variable c below will store the boolean value True
c = (not False)

# The expression below evaluates to False because 1 < 10 is True 
# and not True is False
not 1 < 10

# The expression below evaluates to True because 1 != 1 is False
# and not False is True
not 1 != 1

 

You can combine comparisons

If you have several comparisons and you want to check if at least one of them is True, use the logical operator or

# The expression below evaluates to True because '1 < 5' is True. 
# Note the 'or' operator used to combine the two comparisons.
1 < 5 or 6 > 7

Below, a stores the integer value 5 and b stores the integer value 3. The expression evaluates to True because a > b is true (5 > 3).

a = 5
b = 3

# This expression evaluates to True
a > b or a != 5 or a != 0

The truth table for the or operator. As long as one of the comparisons is True, the result will be True.

Boolean value of comparison A Boolean value of comparison B Boolean value of comparison A or B
True True True
True False True
False True True
False False False

 

If you have several comparisons and you want to check that ALL of them are True, use the logical operator and

# This is False because while '1 < 5' is True, 
# '6 > 7' is False, so in this case not ALL
# comparisons are True.
1 < 5 and 6 > 7

Below, a stores the integer value 5 and b stores the integer value 1. The expression evaluates to False because a != b is True (5 != 1), BUT a < b is False.

a = 5
b = 1

a != b and a < b

The truth table for the and operator. If any of the comparisons is False, the result will be False.

Boolean value of comparison A Boolean value of comparison B Boolean value of comparison A and B
True True True
True False False
False True False
False False False

 

Strings TOP

 

 

 

 

 

  • Python data type used for representing text - think "letters on a piece of string"
  • Strings are immutable (once created, they cannot be modified!)
  • You mark some piece of data as a string by wrapping it in ' or " (e.g. "this is a string", 'hi', "2005")
  • If the text contains a ', use " to mark it as a string and vice-versa (e.g. "she said 'hi'", 'i said "hello"')

 

Example of a single line string

example = "This is a string"
another_example = 'This is also a string'

 

Example of a multiline string

example = """This is
a multiline 
string"""

 

More examples of strings

# Below, we create a string variable called my_text
my_text = 'This is a string'
# You can use double quotes for strings as well.
some_other_text = "This is also a string"

 

Pay attention not to confuse strings with integers!

# Below, count is also a STRING variable, not an integer variable
# Even though it only contains digits, the digits are wrapped 
# in single quotes, so the whole thing becomes a string.

count = '15'

 

Compare the code above, with the code below:

# Below, another_count is an INTEGER variable. Notice
# the lack of single or double quotes.

another_count = 15

 

There is no difference between strings created with single quotes and strings created with double quotes. Having both of those options, allows us to navigate certain tricky situations, as you can see below:

# If your text contains single quotes, use double quotes
# when you create the string.

line = "You can use ' in a string"

# If your text contains double quotes, use single quotes
# when you create the string.

another_line = 'You can also use " in a string'

 

Compare the lines of code above, with the line below, which will actually cause an error. A string containing single quote characters cannot be created using single quotes. Similarly, a string containing double quote characters cannot be created using double quotes. This is because Python gets confused and doesn't know where the string actually ends.

# This code will not work!
bad_string = 'Can you find what's wrong with this string'

However, there is a way around these limitations using certain special characters (escape characters). See the section below on characters with special meaning.

 

Sometimes, it's useful to create empty strings (strings which have no characters). You can easily create these using either single quotes or double quotes, as you can see below:

# The empty_string variable below contains an empty string.
# Same for another_empty_string.

empty_string = ''
another_empty_string = ""

 

Other ways of creating strings

In addition to just using single or double quotes, you can also create strings using the built-in str function (or constructor, if you will). This is useful when you want to convert between data types (process also called type-casting).

# Below, we create a string by type-casting an integer to a string.
string_example = str(5)

# Usually, you need to do this to 'convert' an integer to a string.
some_number = 1234
string_representation = str(some_number)

In the code above, some_number stores an integer, while string_representation stores a string. Basically, the same data (the number 1234) can be represented as either an integer or a string, depending on what kind of transformations or operations you need to do with it. Having a string is useful if you want to append letters at the end of a number, for example. Having an integer is useful if you want to do math operations (e.g. add, multiply, etc.).

 

More examples of using str()

# This will 'convert' a float to a string. 
# 26.3 is a float, but the variable speed
# will be a string.

speed = str(26.3)
# This code will not do much. It will take a string
# and create a string with the same content.

example = str('hello')

 

Characters with special meanings

  • \n is used to indicate a new line
# The code below will print 'hello' on one line and 'world'
# on the next line. 
print("hello \n world")

 

  • \' is used to indicate a single quote inside a string created with single quotes. Basically, the sequence of characters \' is treated as a single quote.
# The code below works! If executed, it will print
# He said 'Hello, sir'

greeting = 'He said \'Hello, sir\'.'
print(greeting)

 

  • \" is used to indicate a double quote inside a string created with double quotes. Basically, the sequence of characters \" is treated as a double quote.
# The code below works! If executed, it will print
# He said "Hello, sir"

greeting = "He said \"Hello, sir\"."
print(greeting)

 

  • \\ is used to indicate a single backslash \
# The code below will print
# C:\Users\JamesBond

file_path = "C:\\Users\\JamesBond"
print(file_path)

 

NOTE: The code below will not work, because \ on its own has a special meaning (it is used to define other special characters, as you can see above). So when Python sees a single backslash, it will look at the character(s) immediately after it and try to interpret the whole thing as a special character.

# THIS WILL NOT WORK!

file_path = "C:\Users\JamesBond"
print(file_path)


# Use this instead

file_path = "C:\\Users\\JamesBond"
print(file_path)


# Or this

file_path = r"C:\Users\JamesBond"
print(file_path)

 

Raw strings

Adding an r before a string tells Python to treat \ as a regular character, as opposed to a character that can be used to define special characters.

# The code below will print
# C:\Users\JamesBond

file_path = r"C:\Users\JamesBond"
print(file_path)

 

# The code below will print:
# Hello \n World

print(r"Hello \n World")


# Compare that to the code below, which will print:
# Hello
#  World

print("Hello \n World")

 

How to concatenate strings

Use the + operator

# The code below will print
# James Bond

agent_name = 'James ' + 'Bond'
print(agent_name)

 

 You can concatenate as many strings as you want.

# The code below will print
# Hello, James Bond

first_name = "James"
last_name = "Bond"
greeting = "Hello, "

print(greeting + first_name + " " + last_name)

 

How to replicate strings

You can replicate strings using the * operator.

# The code below will print
# hahaha

reaction = "ha"
print(reaction * 3)

 

If you multiply by 0, you will get the empty string.

# The code below will print nothing (the empty string)

reaction = 'ha'
print(reaction * 0)

 

String indexing TOP

An index is an integer number that indicates the location of an item in a sequence. Strings are sequences of characters. Therefore, we can use integer numbers to access specific characters or substrings of a string.

 

Positive index

Counts ascending from left to right, starting at 0, as you can see below on the example string "happy birthday".

Negative (reverse) index

Counts descending from right to left, starting at -1, as you can see below on the example string "happy birthday".

 

How to access individual characters in a string using indexes

For the examples below, consider the following example string.

greeting = 'happy birthday'

 

How to access the first character in a string

greeting[0]

 

How to access the last character in a string

greeting[-1]

 

How to access the 4th character in a string

greeting[3]

CAUTION: Because we start counting at 0, the 4th character in the string is actually at index 3. This is easy to verify by counting: the first character is at index 0, the second character is at index 1, the third character is at index 2 and the fourth character is at index 3.

 

How to access parts of a string (substrings) using indexes

This operation is also called slicing. For the examples below, consider the following string:

greeting = "happy birthday"

 

How to get the first 5 characters of a string

greeting[:5]

 

How to get the last 5 characters of a string

greeting[-5:]

 

How to get all characters starting at index 1 (second character), going all the way up to and including the character at index 4 (fifth character)

# The code below will print
# appy

greeting = 'happy birthday'
print(greeting[1:5])

 

How to get every other character in a string

# The code below will print every other character in the original string:
# hpybrha

greeting = 'happy birthday'
print(greeting[::2])

 

How to print every n-th character in a string

# The code below will print
# 0369

numbers = '0123456789'
print(numbers[::3])

 

# The code below will print
# 147

numbers = '0123456789'
print(numbers[1:9:3])

 

General rule for extracting substrings from strings:

 

string_variable[start_index:stop_index:step_size]

 

Where: 

  • start_index indicates the index where we should start
  • end_index indicates the index where we should end (this will not be included in the result!)
  • step_size indicates how many character to skip at each step

Notes:

  • the start_index, end_index and step_size are all optional
  • the element at end_index will not actually be returned
  • step_size can be negative (you can return the reverse of a substring)

 

How to check if a string is part of another string

The easiest way is to use the in operator.

# The code below will evaluate to True
# because 'hello' is part of 'hello world'

'hello' in 'hello world'


# In other words, the variable c below will
# be assigned the value True

c = 'hello' in 'hello world'

 

Capitalization is important when using the in operator

# The code below will evaluate to False
# because 'Hello' is not actually part of 'hello world'
# due to the difference in capitalization.

'Hello' in 'hello world'

 

Pay attention to the data types used when using the in operator

# This does not work because 1 is an integer.
# An integer cannot be part of a string. This
# code will throw an error.

1 in '1234' 

But this will work:

# This works because '1' is a string
# and a string can be part of a string.
# Remember, a string is made of substrings
# (sequences of characters).

'1' in '1234' 

 

Important string methods TOP

How to get the length of a string using the len() function

# The code below will assign the integer
# value 14 to x because there are 14 
# characters in the string stored in the 
# greeting variable.

greeting = "happy birthday"
x = len(greeting)

 

How to turn a string into upper case using the upper() method

NOTE: Because strings are immutable (cannot change once they're created), calling the upper() method will actually create a new version of the string, with all characters in upper case, but will NOT modify the original string stored in the greeting variable.

# The code below prints
# HAPPY

greeting = 'happy'
print(greeting.upper())

 

How to turn a string into lower case using the lower() method

NOTE: Because strings are immutable (cannot change once they're created), calling the lower() method will actually create a new version of the string, with all characters in lower case, but will NOT modify the original string stored in the greeting variable.

# The code below prints
# happy

greeting = 'HaPPy'
print(greeting.lower())

 

How to split a string into substrings using the split() method

NOTE: By default, split() will split based on white spaces, so it can be used to split a string into words. Because strings are immutable (cannot change once they're created), the string that is split will NOT be modified. Instead, a list object will be created with the string subparts.

# The code below will assign x to be the following list
# ['G', '', 'd m', 'rning, sunshine!']

my_string = "Good morning, sunshine!"
x = my_string.split('o')

 

How to join a list if strings into one string using the join() method

NOTE: join() is a method on a string. The string you call join() will be the string that will be inserted between the strings in the list passed as an argument. This list contains the string you want to join.

# After running the code below, the string x will be
# "Spring, Summer, Fall, Winter"

seasons = ['Spring', 'Summer', 'Fall', 'Winter']
x = ", ".join(seasons)


# After running the code below, the string x will be
# "Spring--Summer--Fall--Winter"

seasons = ['Spring', 'Summer', 'Fall', 'Winter']
x = "--".join(seasons)

 

How to remove leading and trailing white space characters from a string using the strip() method

NOTE: The strip() method only removes space characters from the beginning and end of the string. The spaces in the middle of the strings are left untouched. Because strings are immutable (cannot change once they're created), the string will not actually be modified. Instead, the strip() method will create and return a new string object with the white space characters removed.

# The code below will create a variable x that stores the following string:
# 'Python is great!'

text = "   Python is great!        "
x = text.strip()

 

How to check if a string contains a numerical value using the isnumeric() method

# The code below returns True because 
# the string '12' is a numeric value

'12'.isnumeric()

# The code below returns False because
# the string '12a' is not a numeric value

'12a'.isnumeric()

 

How to replace part of a string with another string using the replace() method

NOTE: Because strings are immutable (cannot be modified in place), the replace() method actually creates and returns a new string which contains the replacement. The original string is not modified.

# After running the code below, the variable x will store the string:
# '1 and 2 and 3'

text = 'one and two and three'
x = text.replace('one', '1').replace('two', '2').replace('three', '3')

# The variable text will still store the string:
# 'one and two and three'

 

String formatting TOP

How to format strings using the format() method

# The code below will print:
# 'The name is Bond'

agent = 'Bond'
print('The name is {}'.format(agent))


# The code below will print:
# 'The sum is: 2,340.76. The recipient is Bond.'

agent = 'Bond'
s = 2340.75534343
print('The sum is {:,.2f}. The recipient is {}.'.format(s, agent))


# The code below will print:
# 'My favorite number is 11,101,202.'

fav_number = 11_101_202
print('My favorite number is {:,d}.'.format(fav_number))

 

How to format strings using f-strings

NOTE: To format using f-strings, all you need to do is place an f right before your string (see code examples below). When you do that, you can place variables and formatting specifications between curly braces and the value of those variables will be formatted according to the specifications and embedded into the string.

# The code below will print:
# 'The name is Bond'

agent = 'Bond'
print(f'The name is {agent}')


# The code below will print:
# 'The sum is: 2,340.76. The recipient is Bond.'

agent = 'Bond'
s = 2340.75534343
print(f'The sum is {s:,.2f}. The recipient is {agent}.')


# The code below will print:
# 'My favorite number is 11,101,202.'

fav_number = 11_101_202
print(f'My favorite number is {fav_number:,d}.')

 

Lists TOP

  • Python data types used for storing ordered sequences of objects.
  • The objects inside a list can be of any data type: strings, integers, tuples, dictionaries, even other lists.
  • Lists are wrapped between square brackets []
  • To access items in lists, we can use indexing and slicing (similar to accessing substrings in a string)

 

Examples of lists

 

You can create a list that contains no items (empty list):

empty_list = []

 

You can create lists that contain strings:

cities = ['Paris', 'Rome', 'New York']

 

You can create lists that contain integers and floats:

numbers = [5, 7.2, 4.3, 2]

 

You can create lists that contain mixed data types:

person_info = ['blue', 6, 120.5, ['Amsterdam', 'Barcelona']]

 

You can create lists of lists:

list_of_lists = [[1, 2 , 3 ], [5, 6, 7]]

 

How to create a list from a string (how to extract characters from a string)

Given a string, we can create a list that contains all the characters in the string.

# After the code below gets executed, the 
# variable characters will store the following list of strings:
# ['b', 'a', 's', 'k', 'e', 't', 'b', 'a', 'l', 'l']

sport = 'basketball'
characters = list(sport)

 

List indexing and slicing TOP

 

An index is an integer number that indicates the location of an item in a sequence. Lists are sequences of objects (strings, integers, other lists, etc.). Therefore, we can use integer numbers to access specific items in a list or specific subsets of a list.

 

Positive index

Counts ascending from left to right, starting at 0 (see image above).

 

Negative (reverse) index

Counts descending from right to left, starting at -1 (see image above).

 

How to access individual items in a list using indexes

For the examples below, consider the following example list, consisting of 5 items: the integer 1, the string 'hello', the floating point number 7.56, the list ['a', 'b'] and the dictionary {'Austria': 'Vienna'}.

data = [ 1, 'hello', 7.56, ['a', 'b'], {'Austria': 'Vienna'} ]

 

How to access the first item in a list

data[0]

 

How to access the last item in a list

data[-1]

 

How to access the 4th item in a list

data[3]

CAUTION: Because we start counting at 0, the 4th item (or object, however you prefer to call it) in the list is actually at index 3. This is easy to verify by counting: the first item is at index 0, the second item is at index 1, the third item is at index 2 and the fourth item is at index 3.

 

How to access subsets of a list using indexes

This operation is also called slicing. For the examples below, consider the following list:

data = [ 1, 'hello', 7.56, ['a', 'b'], {'Austria': 'Vienna'} ]

 

How to get the first 3 items in a list

data[:3]

 

How to get the last 3 items in a list

data[-3:]

 

How to get all items starting at index 1 (second item), going all the way up to and including the item at index 3 (fourth item in the list)

# The code below will print
# ['hello', 7.56, ['a', 'b']]

data = [ 1, 'hello', 7.56, ['a', 'b'], {'Austria': 'Vienna'} ]
print(data[1:4])

 

How to get every other item in a list

# The code below will print every other character in the original string:
# [1, 7.56, {'Austria': 'Vienna'}]

data = [ 1, 'hello', 7.56, ['a', 'b'], {'Austria': 'Vienna'} ]
print(data[::2])

 

How to print every n-th item in a list

# The code below will print
# [1, ['a', 'b'], 8]

data = [ 1, 'hello', 7.56, ['a', 'b'], {'Austria': 'Vienna'}, 7, 8 ]
print(data[::3])

 

# The code below will print
# ['hello', {'Austria': 'Vienna'}]

data = [ 1, 'hello', 7.56, ['a', 'b'], {'Austria': 'Vienna'}, 7, 8 ]
print(data[1:5:3])

 

How to reverse a list using the slicing notation

# The code below will print the reverse of the original list:
# [8, 7, {'Austria': 'Vienna'}, ['a', 'b'], 7.56, 'hello', 1]

data = [ 1, 'hello', 7.56, ['a', 'b'], {'Austria': 'Vienna'}, 7, 8 ]
print(data[::-1])

 

General rule for extracting subsets from list:

 

list_variable[start_index:stop_index:step_size]

 

Where: 

  • start_index indicates the index where we should start
  • end_index indicates the index where we should end (this will not be included in the result!)
  • step_size indicates how many items to skip at each step

Notes:

  • the start_index, end_index and step_size are all optional
  • the element at end_index will not actually be returned
  • step_size can be negative (you can return the reverse of a list)

 

List operations TOP

 

How to modify items in a list

NOTE: Lists are mutable objects (they can be modified in place). Therefore, we can change specific items in a list by simply accessing them using the index notation and placing a new item in the list at that specific index.

# The code below will replace the string 'hello' (the item at index 1 in the list)
# with the string 'good-bye' and will print:
# [1, 'good-bye', 7.56, ['a', 'b'], {'Austria': 'Vienna'}, 7, 8]

data = [ 1, 'hello', 7.56, ['a', 'b'], {'Austria': 'Vienna'}, 7, 8 ]
data[1] = 'good-bye'
print(data)

 

How to modify sections of a list at once

NOTE: Lists are mutable objects (they can be modified in place). Therefore, we can change entire sections of a list by simply accessing them using the slicing notation and placing new items in the list at that specific location.

# The code below will replace the second, third and fourth
# items in the list with the integers 2 and 3 and will print:
# [1, 2, 3, {'Austria': 'Vienna'}, 7, 8]

data = [ 1, 'hello', 7.56, ['a', 'b'], {'Austria': 'Vienna'}, 7, 8 ]
data[1:4] = [2, 3]
print(data)

 

How to add items at the end of a list using the append() method

NOTE: Because lists are mutable (they can be modified in place), most list methods will modify the list in place and return the value None, instead of returning a different list with the requested modifications.

# The code below will add the integer 5 to the list

numbers = [1, 2, 3, 4]
numbers.append(5)


# The code below will print:
# [1, 2, 3, 4, 5]

numbers = [1, 2, 3, 4]
numbers.append(5)
print(numbers)


# The code below will print None,
# but the list numbers will still be modified:

numbers = [1, 2, 3, 4]
print(numbers.append(5))

 

How to remove the last item of a list and store it in a variable using the pop() method

# After the code below executes,
# the numbers variable will contain the list [1, 2, 3, 4]
# and the digit variable will contain the integer 5

numbers = [1, 2, 3, 4, 5]
digit = numbers.pop()

 

How to remove the item at a specific index from a list and store it in a variable using the pop() method

# After the code below executes,
# the numbers variable will contain the list [1, 2, 4, 5]
# and the digit variable will contain the integer 3

numbers = [1, 2, 3, 4, 5]
digit = numbers.pop(2)

 

Another way to remove (delete) items from a list, using the del() function

NOTE: The del() function returns the value None. If you want to keep track of the object removed from the list, check out the pop() method above. The del() function will mutate (modify) the list in place!

# After the code below executes,
# the numbers variable will contain the list [1, 2, 4, 5]

numbers = [1, 2, 3, 4, 5]
del(numbers[2])

 

How to concatenate (combine) multiple lists into a single list

NOTE: The + operator is overloaded to allow us to combine multiple lists into a single list.

# After the code below execute, the variable
# all_numbers will store the following list:
# [1, 2, 3, 4, 5]

numbers1 = [1, 2, 3]
numbers2 = [4, 5]
all_numbers = numbers1 + numbers2

# numbers1 and numbers2 will NOT be modified!

 

How to sort a list in ascending order using the sort() method

NOTE: Because lists are mutable (can be modified in place), the sort() method will actually sort the list in place. No other list object will be created.

CAUTION: The sort() method will return None!

# After the code below executes, the variable
# numbers will contain the following list:
# [1, 2, 3, 4, 5]

numbers = [3, 4, 2, 1, 5]
numbers.sort()


# The code below will print None!

numbers = [3, 4, 2, 1, 5]
print(numbers.sort())


# Be careful! DO NOT right code like this.
# It will actually set the variable numbers to None.

numbers = [3, 4, 2, 1, 5]
numbers = numbers.sort() # don't do this!

 

CAUTION: You can only sort a list if all the items in the list can be compared to each other! For example, a list containing both strings and integers, CANNOT be sorted with the sort() method.

# The code below will NOT work. 
# A TypeError will be raised.

numbers = [3, 4, 2, '1', '5']
numbers.sort()

 

How to sort a list in descending order using the sort(reverse=True) method

NOTE: Because lists are mutable (can be modified in place), the sort(reverse=True) method will actually sort the list in place, in reverse order. No other list object will be created.

CAUTION: The sort(reverse=True) method will return None!

# After the code below executes, the variable
# numbers will contain the following list:
# [5, 4, 3, 2, 1]

numbers = [3, 4, 2, 1, 5]
numbers.sort(reverse=True)


# The code below will print None!

numbers = [3, 4, 2, 1, 5]
print(numbers.sort(reverse=True))


# Be careful! DO NOT write code like this.
# It will actually set the variable numbers to None.

numbers = [3, 4, 2, 1, 5]
numbers = numbers.sort(reverse=True) # don't do this!

 

CAUTION: You can only sort a list if all the items in the list can be compared to each other! For example, a list containing both strings and integers, CANNOT be sorted in descending order with the sort(reverse=True) method.

# The code below will NOT work. 
# A TypeError will be raised.

numbers = [3, 4, 2, '1', '5']
numbers.sort(reverse=True)

 

How to reverse a list using the reverse() method

NOTE: The reverse() method DOES NOT sort a list. It simply modifies the list such that the items are in the reverse order. The reverse() method will modify the list in place and will return the value None.

# After the code below executes, the
# numbers variable will store the list:
# [5, 1, 2, 4, 3]

numbers = [3, 4, 2, 1, 5]
numbers.reverse()


# The code below will print None!

numbers = [3, 4, 2, 1, 5]
print(numbers.reverse())


# Be careful! DO NOT write code like this.
# It will actually set the variable numbers to None.

numbers = [3, 4, 2, 1, 5]
numbers = numbers.reverse() # don't do this!

 

How to make a copy of a list

NOTE: Pay attention to the distinction between modifying an object and modifying a copy of an object (which is a different object altogether).

In the example below, other_numbers and numbers refer to the same object (the same piece of memory). Therefore, making a change to other_numbers will actually modify numbers as well! This is often a cause for subtle bugs.

numbers = [1, 2, 3, 4]
other_numbers = numbers

other_numbers[0] = -1

# This will print [-1, 2, 3, 4]
print(other_numbers)

# This will ALSO print [-1, 2, 3, 4] !!
print(numbers)

 

You can make a copy of a list using the copy() method

In the example below, other_numbers and numbers point to different objects. Modifying other_numbers WILL NOT modify numbers.

numbers = [1, 2, 3, 4]
other_numbers = numbers.copy()

other_numbers[0] = -1

# This will print [-1, 2, 3, 4]
print(other_numbers)

# This will print [1, 2, 3, 4]
print(numbers)

 

You can also quickly make a copy of a list using the [:] index notation

In the example below, other_numbers and numbers point to different objects. Modifying other_numbers WILL NOT modify numbers.

numbers = [1, 2, 3, 4]
other_numbers = numbers[:]

other_numbers[0] = -1

# This will print [-1, 2, 3, 4]
print(other_numbers)

# This will print [1, 2, 3, 4]
print(numbers)

 

Tuples TOP

  • Python data types used for storing ordered sequences of objects.
  • The objects inside a tuple can be of any data type: strings, integers, tuples, dictionaries, lists, etc.
  • Tuples are often wrapped between parentheses ()
  • To access items in tuples, we can use indexing and slicing (similar to accessing substrings in a string)
  • Items in a tuple are comma separated
  • Tuples are immutable: once created, they cannot be modified!
    • you cannot add items to a tuple
    • you cannot remove items from a tuple
    • you cannot replace the objects inside a tuple (however, if the objects can be modified in place, that's ok)
  • Tuples are generally more space-efficient than lists (important if you have to store large amounts of data)
  • Tuples are generally faster to process than lists (again, important if you have large amounts of data to store / process)

 

Examples of tuples

You can create a tuple that contains no items (empty tuple):

empty_tuple = ()

 

You can create tuples that contain strings:

cities = ('Paris', 'Rome', 'New York')

 

What defines a tuple are not the parentheses, but rather the commas between the items:

# The variable cities below also stores a tuple,
# even though we did not specify the parentheses!

cities = 'Paris', 'Rome', 'New York'

 

Single item tuples still require commas:

Commas are very important for defining a tuple and are even required if the tuple contains a single item. Overlooking this fact often leads to subtle bugs. If your tuple has a single item, you must include a comma after the item. Generally, we do not include trailing commas if the tuple has 2 or more items.

# This is a tuple
numbers = (1,)

# This is also a tuple
numbers = 1,

 

These are also tuples, though, as mentioned, the trailing commas are not common if the tuple has 2 or more items:

# This is a tuple (not common)
numbers = (1, 2,)

# This is also a tuple (not common)
numbers = 1, 2,

 

The code below does NOT define a tuple. Python evaluates the expression between the parentheses and assigns the resulting value to the variable. Since there is no trailing comma (which would indicate a tuple), the entire expression is evaluated to an integer.

# This is NOT a tuple (the comma is missing). This is an integer!
numbers = (1)

 

You can create tuples that contain integers and floats:

numbers = (5, 7.2, 4.3, 2)

 

You can create tuples that contain mixed data types:

person_info = ('blue', 6, 120.5, ['Amsterdam', 'Barcelona'])

 

You can create tuples of tuples:

tuple_of_tuples = ((1, 2 , 3), (5, 6, 7))

 

How to create a tuple from a string (how to extract characters from a string)

Given a string, we can create a tuple that contains all the characters in the string.

# After the code below gets executed, the 
# variable characters will store the following tuple of strings:
# ('b', 'a', 's', 'k', 'e', 't', 'b', 'a', 'l', 'l')

sport = 'basketball'
characters = tuple(sport)

 

How to create a tuple from a list

numbers = tuple([1, 2, 3, 4])

 

Tuple indexing and slicing TOP

 

An index is an integer number that indicates the location of an item in a sequence. Tuples are immutable sequences of objects (strings, integers, other lists, other tuples, etc.). Therefore, we can use integer numbers to access specific items in a tuple or specific subsets of a tuple.

 

Positive index

Counts ascending from left to right, starting at 0 (see image above).

 

Negative (reverse) index

Counts descending from right to left, starting at -1 (see image above).

 

How to access individual items in a tuple using indexes

For the examples below, consider the following example list, consisting of 5 items: the integer 7, the string 'phone', the floating point number 6.31, the list ['x', 'y'] and the dictionary {'Germany': 'Berlin'}.

data = ( 7, 'phone', 6.31, ['x', 'y'], {'Germany': 'Berlin'} )

 

How to access the first item in a tuple

data[0]

 

How to access the last item in a tuple

data[-1]

 

How to access the 4th item in a tuple

data[3]

CAUTION: Because we start counting at 0, the 4th item (or object, however you prefer to call it) in the tuple is actually at index 3. This is easy to verify by counting: the first item is at index 0, the second item is at index 1, the third item is at index 2 and the fourth item is at index 3.

 

How to access subsets of a tuple using indexes

This operation is also called slicing. For the examples below, consider the following tuple:

data = ( 7, 'phone', 6.31, ['x', 'y'], {'Germany': 'Berlin'} )

 

How to get the first 3 items in a tuple

data[:3]

This code will return the tuple (7, 'phone', 6.31)

 

How to get the last 3 items in a tuple

data[-3:]

This code will return the tuple (6.31, ['x', 'y'], {'Germany': 'Berlin'})

 

How to get all items starting at index 1 (second item), going all the way up to and including the item at index 3 (fourth item in the tuple)

# The code below will print
# ('phone', 6.31, ['x', 'y'])

data = ( 7, 'phone', 6.31, ['x', 'y'], {'Germany': 'Berlin'} )
print(data[1:4])

 

How to get every other item in a tuple

# The code below will print every other character in the original string:
# (7, 6.31, {'Germany': 'Berlin'})

data = ( 7, 'phone', 6.31, ['x', 'y'], {'Germany': 'Berlin'} )
print(data[::2])

 

How to print every n-th item in a tuple

# The code below will print
# (7, ['x', 'y'], 'a')

data = ( 7, 'phone', 6.31, ['x', 'y'], {'Germany': 'Berlin'}, (1, 2), 'a' )
print(data[::3])

 

# The code below will print
# ('phone', {'Germany': 'Berlin'})

data = ( 7, 'phone', 6.31, ['x', 'y'], {'Germany': 'Berlin'}, (1, 2), 'a' )
print(data[1:5:3])

 

How to reverse a tuple using the slicing notation

# The code below will print the reverse of the original tuple:
# ('a', (1, 2), {'Germany': 'Berlin'}, ['x', 'y'], 6.31, 'phone', 7)

data = ( 7, 'phone', 6.31, ['x', 'y'], {'Germany': 'Berlin'}, (1, 2), 'a' )
print(data[::-1])

NOTE: The code above DOES NOT modify the tuple. Instead, a new tuple object is created which has the exact items as the original tuple stored in the data variable, but in reverse order.

 

General rule for extracting subsets from tuple:

 

tuple_variable[start_index:stop_index:step_size]

 

Where: 

  • start_index indicates the index where we should start
  • end_index indicates the index where we should end (this will not be included in the result!)
  • step_size indicates how many items to skip at each step

Notes:

  • the start_index, end_index and step_size are all optional
  • the element at end_index will not actually be returned
  • step_size can be negative (you can return the reverse of a tuple)

 

Tuple operations TOP

 

You CANNOT add new items to a tuple

# The code below WILL NOT work

numbers = (1, 2, 3)
numbers.append(4)

 

You CANNOT remove items from a tuple

# The code below WILL NOT work

numbers = (1, 2, 3)
del(numbers[0])

 

You CANNOT replace objects in a tuple with other objects

# The code below WILL NOT work

numbers = (1, 2, 3)
numbers[0] = 4


# The code below WILL NOT work

letters = ('a', 'b', 'c')
letters[0] = 'x'


# The code below WILL NOT work

data = ((1, 2), (3, 4), (5, 6))
data[0] = (7, 8)


# The code below WILL NOT work

data = ([1, 2], [3, 4], [5, 6])
data[0] = 7

 

You CAN modify objects in a tuple, if the objects themselves are mutable (e.g. lists, dictionaries)

In the example below, the code works because we are not modifying the tuple itself. Instead, we are modifying a list inside a tuple. A list is a mutable object, so it can be modified in place. The tuple doesn't care whether an object changes its contents. What it cares about is that no new object replaces an existing object.

# The code below WILL work.
# After the code executes, data will be:
# ([2, 2], [3, 4], [5, 6])

data = ([1, 2], [3, 4], [5, 6])
data[0][0] = 2

 

Dictionaries TOP

  • Python data types that consist of pairs of keys mapped to values
  • They are unordered collections of data
  • The data access pattern usually involves supplying a key and getting the value associated with the key. This is in contrast to lists, tuples and strings, where access is done via an index.
  • Dictionaries are mutable data types. They can be changed in place (pairs can be added, removed, modified, etc.)
  • Dictionaries can be nested (e.g. dictionaries can contain other dictionaries)
  • The keys in a dictionary can be any object, provided that the data type of the object is immutable
    • Strings, integers, floats, booleans, tuples CAN be dictionary keys
    • Lists, dictionaries CANNOT be dictionary keys

 

 

Examples of dictionaries

You can create an empty dictionary, containing no pairs:

empty_dictionary = {}

 

You can create dictionaries mapping any combination of objects. The only requirement is that the keys are immutable:

placements = { 1: 'France', 2: 'Italy' }

food_menu = { 'first': 'soup', 'second': 'pizza' }

numbers = { 0: 4.3, 1: 4.0 }

data = { 21: ['Mary', 'Jack', 'Jill'], 22: (53, 53) }

 

Dictionaries can include other dictionaries as values:

countries = {
    'Europe': { 
        'Germany': 'Berlin', 
        'Austria': 'Vienna', 
        'Sweden': 'Stockholm'
    },
    'North America': {
       'USA': 'Washington, D.C.', 
       'Canada': 'Ottawa'
   }
}

 

How to create dictionaries from list of tuples

Sometimes it's useful to be able to create dictionaries from other data structures. Some of the more common data structures that can be easily turned into dictionaries are:

  • list of tuples
  • list of lists
# After the code below executes, the variable
# data_dictionary will store the following dictionary:
# {'a': 1, 'b': 2, 'c': 3}

data = [ ('a', 1), ('b', 2), ('c', 3) ]
data_dictionary = dict(data)
# After the code below executes, the variable
# data_dictionary will store the following dictionary:
# {'x': 24, 'y': 25, 'z': 26}

data = ( ('x', 24), ('y', 25), ('z', 26) )
data_dictionary = dict(data)

 

Dictionary operations TOP

 

How to access data in a dictionary

Data in a dictionary cannot be accessed by index. Instead, we usually access data in a dictionary by providing a key.

person_attrs = { 
    'eye_color': 'blue', 
    'height': 5.7, 
    'weight': 120.5, 
    'vacation_cities': ['Amsterdam', 'Barcelona'], 
    'ids': {
        'ssn': '111-00-0000', 
        'license': 'S000001'
    }
}

# The code below prints 120.5, which is the value
# that corresponds to the key 'weight' in the dictionary
# defined above:
print(person_attrs['weight'])

# The code below prints the '111-00-0000'
print(person_attrs['ids']['ssn'])

NOTE: You can keep chaining square brackets to chain indexing operations. In the example above, person_attrs is a dictionary. person_attrs['ids'] is also a dictionary, because the key 'ids' is mapped to the dictionary {'ssn': '111-00-0000', 'license': 'S000001'}. Therefore, person_attrs['ids']['ssn'] makes sense: it's a way to access the key 'ssn' in the dictionary mapped to the key 'ids' in the person_attrs dictionary.

 

NOTE: The specified key must exist. If the specified key does not exist, you will get a KeyError. See the get() method below for a way to access data that will not result in a potential exception.

 

How to access data in dictionaries that contain nested data structures

Consider the following dictionary:

data = {"key_1": 27, 3: [5, 6.0, "number three"]}

To access and print the value 6.0, we need to write code like this:

data[3][1]

 

Consider the following dictionary, which stores information about high and low prices for fictitious stocks xyz and abc:

data = { 
    'market': { 
        'prices': [ 
            { 'xyz': { 'high': 5670, 'low': 5589 } }, 
            { 'abc': { 'high': 545, 'low': 479 } }
        ] 
    } 
}

To access the low price for stock abc from this dictionary, we would need to write code like this:

data['market']['prices'][1]['abc']['low']

TIP: Avoid deeply nested data structures like the one above! They can be tricky to access and can lead to confusion and bugs.

 

How to add new pairs to a dictionary

# The code below adds the pair 'c': 3
# to the dictionary stored in the letters variable

letters = {'a': 1, 'b': 2}
letters['c'] = 3

 

In a dictionary pair, the value can be any object, including lists:

# After the code below executes, data will be:
# { 'x': 56, 'y': [1, 2, 3, 4] }

data = { 'x': 56 }
data['y'] = [1, 2, 3, 4]

 

And even other dictionaries:

# After the code below executes, data will be:
# { 'x': 56, 'y': {'greeting': 'hello'} }

data = { 'x': 56 }
data['y'] = {'greeting': 'hello'}

 

How to update the value mapped to an existing key in a dictionary

You can update a dictionary using the same notation used for accessing data:

# After the code below executes, letters becomes:
# { 'a': 1, 'b': 2, 'c': 100 }

letters = { 'a': 1, 'b': 2, 'c': 3 }
letters['c'] = 100

 

How to delete a pair from a dictionary

Consider the dictionary below:

data = { 'one': 1, 'two': 2, 'three': 3 }

You can delete the pair 'three': 3 using the del function as follows:

del(data['three'])

 

How to check if a dictionary contains a given key using the in operator

letters = {'a': 1, 'b': 2, 'c': 3}

# The variable found below will store the
# boolean value True because 'a' is indeed 
# a key in the letters dictionary:

found = 'a' in letters


# The variable found below will store the
# boolean value False because 'z' is NOT
# a key in the letters dictionary:

found = 'z' in letters

 

Dictionary methods TOP 

 

How to get the list of dictionary keys using the keys() method

# After the code below executes, 
# dictionary_keys will store the list
# of all the keys in the letters dictionary:
# 'a', 'b', and 'c'

letters = { 'a': 1, 'b': 2, 'c': 3 }
dictionary_keys = letters.keys()

 

How to get the list of dictionary values using the values() method

# After the code below executes, 
# dictionary_values will store the list
# of all the values in the letters dictionary:
# 1, 2, and 3

letters = { 'a': 1, 'b': 2, 'c': 3 }
dictionary_values = letters.values()

 

How to get a list of dictionary pairs using the items() method

The code below will print the dictionary pairs as a list of tuples, where the first item in each tuple is the key and the second item in each tuple is the value mapped to that key.

letters = { 'a': 1, 'b': 2, 'c': 3 }
print(letters.items())

The code above prints:

dict_items([('a', 1), ('b', 2), ('c', 3)])

dict_items is a data type, just like lists, tuples, etc., designed for storing list of dictionary pairs. For all intents and purposes, the object above is equivalent to:

[('a', 1), ('b', 2), ('c', 3)]

 

How to access data in a dictionary using the get() method

This approach has the added advantage that if the specified key does not exist, an exception will not be thrown. Instead, the value specified in the second argument of the get() method will be returned as the default value.

letters = {'a': 1, 'b': 2, 'c': 3}

# This code will assign the value 2 
# to the variable code because the
# specified key 'b' is part of the dictionary
# and it is mapped to the value 2:

code = letters.get('b', None)


# This code will assign the value None
# to the variable code because the 
# specified key 'z' does not exist in the
# dictionary:

code = letters.get('z', None)

 

Conditionals (if... elif... else) TOP 

if current_day == 'Monday':
    print('meh')
elif current_day == 'Wednesday':
    print('hump day')
elif current_day == 'Thursday' or current_day == 'Friday':
    print('almost weekend')
else:
    print('yay')

 

  • Python programs are executed top to bottom, line by line.
  • Conditionals are code constructs that allow us to control which of the lines of code get executed in different circumstances.
  • Conditionals are a way to add 'logic' to our code.
  • You can have as many elif branches as you need associated with ONE if branch.
  • You can have one default else branch that will execute if none of the other branches executed.
  • You can have at most ONE else branch.
  • Check out the section on comparisons to learn more about the operators you can use when writing conditionals.

 

The structure of a simple if statement

 

 

Examples

The elif and else branches are optional

The code below will print 'Turn heat off'. The way it works is as follows: the variable temperature will be compared with 71. Because temperature = 75, the expression temperature < 71 will be False, and so next we'll look at the condition on the elif branch. In this case, temperature > 71 is True, so the code INDENTED underneath the elif branch will execute, printing 'Turn heat off'.

temperature = 75

if temperature < 71:
    print('Turn heat on')
elif temperature > 71:
    print('Turn heat off')

 

You can have nested if statements

# The code below will print:
# "go to work"

weather_is_nice = True
current_day = "Tuesday"

if weather_is_nice:
    if (current_day == "Saturday" or current_day == "Sunday"):
        print("go out")
    else:
        print("go to work")
else:
    print("stay home")

 

Remember that objects in Python can be cast to booleans

Python does this automatically in some cases. For example, if you have a list and you want to execute some code if the list is not empty, you can simply write code like this:

# Python will automatically cast the list some_data
# below to a boolean. Because some_data is an empty
# list, it will be cast to the boolean value False. 
# Therefore, the code below will print 'The data is missing'.

some_data = []

if some_data:
    print('We have data.')
else:
    print('The data is missing.')

NOTE: The code above is the 'pythonic way' of writing the conditional in this case. The comparison with the empty list object is redundant. Don't do this:

# DON'T write code like this!
# It's technically correct, but it's
# not preferred. 

some_data = []

if some_data == []:
    print('We have data.')
else:
    print('The data is missing.')

 

Ciprian Stratulat

CTO | Software Engineer

Ciprian Stratulat

Ciprian is a software engineer and the CTO of Edlitera. As an instructor, Ciprian is a big believer in first building an intuition about a new topic, and then mastering it through guided deliberate practice.

Before Edlitera, Ciprian worked as a Software Engineer in finance, biotech, genomics and e-book publishing. Ciprian holds a degree in Computer Science from Harvard University.