Show Menu
Cheatography

Cheat sheet for Python Topics Cheat Sheet (DRAFT) by

Cheat sheet for python lists

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Python Lists

#Defin­ition:
A list is a mutable collection of ordered elements enclosed in square brackets [].
Lists can contain any type of data, including other lists.
#Creating a List :
Lists can be created using square brackets [] or the list() constr­uctor.
#Using Square brackets:
my_list = [1, 2, 3]
# Using the list () constr­uctor:
my_list = list([1, 2, 3])
myList = list(r­ang­e(5)) # a list with five items [0, 1, 2, 3, 4]
myList = [i*2 for i in range(5)] a list with five items [0, 2, 4, 6, 8]
Accessing Elements :
Elements in a list can be accessed using indexing or slicing.
# Accessing an element using indexing :
my_list = [1, 2, 3, 4, 5]
Print(my_list[0]) # output: 1 accesses the first element in the list (1).
# Accessing a slice of elements using slicing :
print(­my_­lis­t[1­:4])) # Output: [2, 3, 4]
Some examples on indexing and slicing :
my_list = ['apple', 'banana', 'cherry']
print(my_list[1]) # Output: banana accesses the second element in the list ('bana­na').
print(my_list[-1]) # Output: cherry accesses the last element in the list ('cher­ry').
print(my_list[1:]) # Output: ['banana', 'cherry'] accesses all elements in the list from the second element to the end
Modifying Elements :
Elements in a list can be modified using indexing or slicing.
my_list = [1, 2, 3]
my_list[0] = 4
print(­my_­list) # Output: [4, 2, 3]
Some Examples to modify elements using index and slice()
my_list = ['apple', 'banana', 'cherry']
my_list[1] = 'orange' changes the second element in the list to 'orange'.
my_lis­t.a­ppe­nd(­'gr­ape') adds 'grape' to the end of the list.
my_lis­t.e­xte­nd(­['k­iwi', 'water­mel­on']) adds the list ['kiwi', 'water­melon'] to the end of the list.
my_lis­t.r­emo­ve(­'ch­erry') removes the element 'cherry' from the list.
my_lis­t.p­op(0) removes and returns the first element in the list ('apple').
List Methods :
Lists have many built-in methods, including:
# Using append() method :
my_list = [1, 2, 3]
my_list.append(4)
print(my_list)
# Output: [1, 2, 3, 4]
# Using extend() method :
my_lis­t.e­xte­nd([5, 6])
print(my_list)
# Output: [1, 2, 3, 4, 5, 6]
# Using insert() method :
my_lis­t.i­nse­rt(0, 0)
print(my_list)
# Output: [0, 1, 2, 3, 4, 5, 6]
# Using remove() method :
my_lis­t.r­emo­ve(3)
print(my_list)
# Output: [0, 1, 2, 4, 5, 6]
# Using pop() method :
my_lis­t.p­op(2)
print(my_list)
# Output: [0, 1, 4, 5, 6]
# Using sort() method :
my_lis­t.s­ort()
print(my_list)
# Output: [0, 1, 4, 5, 6]
# Using reverse() method :
my_lis­t.r­eve­rse()
print(my_list)
# Output: [6, 5, 4, 1, 0]
Copying a List:
my_list = ['apple', 'banana', 'cherry']
new_list = my_lis­t.c­opy()
Nested Lists:
my_list = [[1, 2], [3, 4]]
print(my_list[0][1]) # Output: 2
List Functions:
sum(my­_list)
all(my_list)
any(my_list)
enumerate(my_list)
zip(my_list1, my_list2)
List Compre­hen­sions :
List compre­hen­sions provide a concise way to create lists based on existing lists.
# Creating a new list using list compre­hension :
my_list = [1, 2, 3, 4, 5]
new_list = [x * 2 for x in my_list]
print(new_list) # Output: [2, 4, 6, 8, 10]
my_list = [x for x in range(1, 6)]
even_list = [x for x in range(1, 11) if x % 2 == 0]
Advantage of Using Lists :
Lists are mutable, which makes them more flexible to use than tuples.
 

Tuples In Python

What are Tuples?
A tuple is an ordered, immutable collection of elements.
In Python, tuples are created using parent­heses ()
and the elements are separated by commas ,.
Creating Tuples
# Create an empty tuple
my_tuple = ()
# Create a tuple with elements
my_tuple = (1, 2, 3)
# Create a tuple with a single element
my_tuple = (1,)
# Create a tuple without parentheses
my_tuple = 1, 2, 3
Accessing Elements
Tuples are ordered collec­tions,
So you can access individual elements using indexing.
my_tuple = ('apple', 'banana', 'cherry')
# Access the first element
print(­my_­tup­le[0]) # Output: 'apple'
# Access the last element
print(­my_­tup­le[-1]) # Output: 'cherry'
Immuta­bility
Tuples are immutable, which means that
you can't modify their contents after they're created.
my_tuple = (1, 2, 3)
# Trying to modify the first element will result in an error
my_tuple[0] = 4 # TypeError: 'tuple' object does not support item assignment
Tuple Methods
Tuples have a few built-in methods that you can use:
count()
Returns the number of times a specified value occurs in a tuple.
my_tuple = (1, 2, 2, 3, 2, 4)
# Count the number of times the value 2 appears
print(my_tuple.count(2)) # Output: 3
index()
Returns the index of the first occurrence of a specified value in a tuple.
my_tuple = (1, 2, 2, 3, 2, 4)
# Find the index of the first occurrence of the value 3
print(my_tuple.index(3)) # Output: 3
Tuple Unpacking
You can also "­unp­ack­" tuples, which allows
you to assign the values in a tuple to separate variables.
my_tuple = ('John', 'Doe', 30)
# Unpack the tuple into separate variables
first_name, last_name, age = my_tuple
print(first_name) # Output: 'John'
print(last_name) # Output: 'Doe'
print(age) # Output: 30
Advantages of Tuples
Tuples are immutable, so they're useful for storing data that shouldn't be changed accidentally.
Tuples are faster than lists, since they're smaller and can be stored more effici­ently in memory.
Tuples can be used as dictionary keys, while lists cannot.
 

Dictio­naries in Python

Creating a dictionary
# Empty dictionary
my_dict = {}
# Dictionary with initial values
my_dict = {"ke­y1": "­val­ue1­", "­key­2": "­val­ue2­", "­key­3": "value3"}
# Using the dict() constructor
my_dict = dict(k­ey1­="va­lue­1", key2="v­alu­e2", key3="v­alu­e3")
Accessing values
# Accessing a value by key
my_dict["key1"] # returns "value1"
# Using the get() method to avoid KeyError
my_dict.get("key1") # returns "value1"
my_dict.get("key4") # returns None
# Using the get() method with a default value
my_dict.get("key4", "­def­aul­t_v­alu­e") # returns "­def­aul­t_v­alu­e"
Adding and updating values
# Adding a new key-value pair
my_dict["key4"] = "value4"
# Updating a value
my_dict["key1"] = "new_value1"
# Using the update() method to add/update multiple values
my_dict.update({"key5": "­val­ue5­", "­key­6": "­val­ue6­"})
Removing values
# Removing a key-value pair
del my_dict["key1"]
# Using the pop() method to remove a key-value pair and return the valmy_­dic­t.p­op(­"­key­2") # returns "value2"ue

# Using the pop() method with a default value
my_dict.pop("key4", "­def­aul­t_v­alu­e") # returns "default_value"
# Using the clear() method to remove all key-value pairs
my_dict.clear()
Other methods
# Getting the number of key-value pairs
len(my_dict)
# Checking if a key exists in the dictionary
"key1" in my_dict
# Getting a list of keys
my_dict.keys()
# Getting a list of values
my_dict.values()
# Getting a list of key-value pairs as tuples
my_dict.items()
Advantages of Python dictio­naries
Python dictio­naries offer fast lookups, flexible key/value storage,
dynamic resizing, efficient memory usage, and ease of use, making them a versatile
and powerful data structure widely used in Python progra­mming.

Python strings

Creating strings
my_string = "­Hello, World!­" # double quotes
my_string = 'Hello, World!' # single quotes
my_string = "­"­"­Hello, World!­"­"­" # triple quotes (for multiline strings)
Accessing characters in a string
my_string = "­Hello, World!"
print(my_string[0]) # H
print(my_string[-1]) # !
Slicing strings
my_string = "­Hello, World!"
print(my_string[0:5]) # Hello
print(my_string[7:]) # World!
print(my_string[:5]) # Hello
print(my_string[::2]) # Hlo ol!
String methods
my_string = "­Hello, World!"
print(my_string.upper()) # HELLO, WORLD!
print(my_string.lower()) # hello, world!
print(my_string.replace("Hello", "­Hi")) # Hi, World!
print(my_string.split(",")) # ['Hello', ' World!']
print(my_string.strip()) # Hello, World! (remove whitespace)
print(len(my_string)) # 13 (length of the string)
Concat­enating strings
str1 = "Hello"
str2 = "World"
print(str1 + " " + str2) # Hello World
String formatting
name = "John"
age = 30
print("My name is {} and I'm {} years old".fo­rma­t(name, age))
# My name is John and I'm 30 years old
# f-strings (Python 3.6+)
print(f"My name is {name} and I'm {age} years old")
# My name is John and I'm 30 years old
Encoding and decoding strings
my_string = "­Hello, World!"
encoded_string = my_str­ing.en­cod­e("u­tf-­8") # b'Hello, World!'
decoded_string = encode­d_s­tri­ng.d­ec­ode­("ut­f-8­") # Hello, World!
Advantages of strings in Python
Strings in Python have several advant­ages, including their flexibility,
ease of use, and extensive library of built-in string methods,
making it easy to manipulate and format text data for various purposes
such as data analysis, web develo­pment, and automation tasks.