Python Quick Cheatsheet
This post is based on here
Variables
Python has no command for declaring a variable. A variable is created the moment you first assign a value to it. Variables do not need to be declared with any particular type, and can even change type after they have been set.
If you want to specify the data type of a variable, this can be done with casting.
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
String variables can be declared either by using single or double quotes:
x = "John"
# is the same as
x = 'John'
- assign values to multiple variables in one line:
x, y, z = "Orange", "Banana", "Cherry"
- assign the same value to multiple variables in one line:
x = y = z = "Orange"
unpack a collection:
fruits = ["apple", "banana", "cherry"] x, y, z = fruits
or use asterik
*
to unpacks all the iterable variables that haven't been assigned to any variable:start, *middle, end = [1, 2, 3, 4, 5] print(start) # 1 print(end) # 5 print(middle) # [2, 3, 4]
In the print()
function, when you try to combine a string and a number with the +
operator, Python will give you an error:
x = 5
y = "John"
# TypeError: unsupported operand type(s) for +: 'int' and 'str'
print(x + y)
The best way to output multiple variables in the print()
function is to separate them with commas, which even support different data types:
x = 5
y = "John"
# 5 John
print(x, y)
Data Type
- Text Type:
str
- Numeric Types:
int
,float
,complex
- Sequence Types:
list
,tuple
,range
- Mapping Type:
dict
- Set Types:
set
,frozenset
- Boolean Type:
bool
- Binary Types:
bytes
,bytearray
,memoryview
None Type:
NoneType
# list x = ["apple", "banana", "cherry"] # tuple x = ("apple", "banana", "cherry") # set x = {"apple", "banana", "cherry"} # dict x = {"name" : "John", "age" : 36}
Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string.
a = "Hello, World!"
print(a[1])
String
Slicing String
b = "Hello, World!"
print(b[2:5])
print(b[:5])
print(b[2:])
print(b[-5:-2])
Functions
strip()
: removes any whitespace from the beginning or the enda = " Hello, World! " print(a.strip()) # returns "Hello, World!"
split()
: plits the string into substrings if it finds instances of the separatora = "Hello, World!" print(a.split(",")) # returns ['Hello', ' World!']
Other methods:
endswith()
,startswith()
.
Format String
F-String:
To specify a string as an f-string, simply put an f in front of the string literal, and add curly brackets {} as placeholders for variables and other operations.
age = 36
txt = f"My name is John, I am {age}"
print(txt)
A placeholder can include a modifier to format the value.
A modifier is included by adding a colon :
followed by a legal formatting type, like .2f
which means fixed point number with 2 decimals:
price = 59
txt = f"The price is {price:.2f} dollars"
print(txt)
Operator
%
: modulus**
: exponetiation//
: floor division- logical:
and
,or
,not
- membership:
in
,not in
Bitwise
&
: AND|
: OR^
: XOR~
: NOT<<
: left shift>>
: right shift
Python List
List items are ordered, changeable, and allow duplicate values.
A list can contain different data types: list1 = ["abc", 34, True, 40, "male"]
Create list:
thislist = ["apple", "banana", "cherry"] thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
- Use
len()
to get the length of a list. change an item:
thislist = ["apple", "banana", "cherry"] thislist[1] = "blackcurrant" # or thislist[1:3] = ["blackcurrant", "watermelon"] # or insert more items than you replace thislist[1:2] = ["blackcurrant", "watermelon"] # or insert less items: thislist[1:3] = ["watermelon"]
insert an item:
thislist = ["apple", "banana", "cherry"] thislist.insert(2, "watermelon") # ['apple', 'banana', 'watermelon', 'cherry']
append an item:
thislist = ["apple", "banana", "cherry"] thislist.append("orange")
or, extend list from another list
thislist = ["apple", "banana", "cherry"] tropical = ["mango", "pineapple", "papaya"] thislist.extend(tropical)
remove an item:
If there are more than one item with the specified value, the remove() method removes the first occurrence:thislist = ["apple", "banana", "cherry", "banana", "kiwi"] thislist.remove("banana") print(thislist) # ['apple', 'cherry', 'banana', 'kiwi']
To remove item at specified index, use
pop()
:thislist = ["apple", "banana", "cherry"] thislist.pop(1) print(thislist) # ['apple', 'cherry']
If you do not specify the index, the
pop()
method removes the last item.
Or, usedel
:del thislist[0]
,del thislist
Loop over
thislist = ["apple", "banana", "cherry"] for x in thislist: print(x) for i in range(len(thislist)): print(thislist[i])
- list comprehension:
newlist = [expression for item in iterable if condition == True]
sort a list:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"] thislist.sort() # sort in ascending order by default # or in descending order thislist.sort(reverse = True)
customize your own function by using the keyword argument
key = function
:def myfunc(n): return abs(n - 50) thislist = [100, 50, 65, 82, 23] thislist.sort(key = myfunc) print(thislist)
- reverse a list, use
reverse()
Python Tuple
Tuple items are ordered, unchangeable, and allow duplicate values.
Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created.
Tuple items are indexed, the first item has index [0]
, the second item has index [1]
etc.
create a tuple
tuple1 = ("abc", 34, True, 40, "male") # To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple. thistuple = ("apple",)
access items
You can access tuple items by referring to the index number, inside square bracketsthistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango") print(thistuple[2:5]) print(thistuple[1])
To determine if a specified item is present in a tuple use the in keyword:
if "apple" in thistuple: print("Yes, 'apple' is in the fruits tuple")
Join tuples
To join two or more tuples you can use the + operator:tuple1 = ("a", "b" , "c") tuple2 = (1, 2, 3) tuple3 = tuple1 + tuple2 print(tuple3)
If you want to multiply the content of a tuple a given number of times, you can use the * operator:
fruits = ("apple", "banana", "cherry") mytuple = fruits * 2 # ('apple', 'banana', 'cherry', 'apple', 'banana', 'cherry') print(mytuple)
Why tuple over list ?
- immutability: Tuples provide a guarantee that their content won’t change.
- Faster Performance: Because tuples are immutable, they are more lightweight and faster to iterate over compared to lists.
Hashability: Tuples are hashable if their elements are hashable. This makes them usable as keys in dictionaries and elements in sets:
coords = (10, 20) locations = {coords: "Park"}
Semantic Meaning: Tuples often represent a fixed collection of related elements, like coordinates (x, y), or return values from a function.
def divide(a, b): return a // b, a % b # Returns a tuple quotient, remainder = divide(10, 3)
Python Set
Set items are unordered, unchangeable, and do not allow duplicate values.
Note: Once a set is created, you cannot change its items, but you can remove items and add new items.
add item:
thisset = {"apple", "banana", "cherry"} # Or, # thisset = set(("apple", "banana", "cherry")) # note the double round-brackets thisset.add("orange")
to add items from another set
thisset = {"apple", "banana", "cherry"} tropical = {"pineapple", "mango", "papaya"} thisset.update(tropical)
- To remove an item in a set, use the
remove()
, or thediscard()
method.
If the item to remove does not exist,remove()
will raise an error. You can also use thepop()
method to remove an item, but this method will remove a random item. union of two sets, use
union()
or|
set1 = {"a", "b", "c"} set2 = {1, 2, 3} set3 = set1.union(set2) # myset = set1.union(set2, set3, set4) # Or set3 = set1 | set2 # myset = set1 | set2 | set3 |set4
intersection of sets, use
intersection()
or&
set1 = {"apple", "banana", "cherry"} set2 = {"google", "microsoft", "apple"} set3 = set1.intersection(set2) # Or set3 = set1 & set2
difference()
: will return a new set that will contain only the items from the first set that are not present in the other setset1 = {"apple", "banana", "cherry"} set2 = {"google", "microsoft", "apple"} set3 = set1.difference(set2) # Or set3 = set1 - set2
symmetric_difference()
: will keep only the elements that are NOT present in both sets.set1 = {"apple", "banana", "cherry"} set2 = {"google", "microsoft", "apple"} set3 = set1.symmetric_difference(set2) # Or set3 = set1 ^ set2
issubset()
: returns whether another set contains this set or not, or use<
.issuperset()
: returns whether this set contains another set or not, or use>
.
Python Dictionary
The values in dictionary items can be of any data type:
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
- access items:
x = thisdict["model"]
, orthisdict.get("model")
keys()
: will return a list of all the keys in the dictionary.values()
: will return a list of all the values in the dictionary.remove items: use
pop()
ordel
:thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict.pop("model") # Or del thisdict["model"]
loop through dictionaries
# Print all key names in the dictionary, one by one for x in thisdict: print(x) # Or # for x in thisdict.keys(): # Print all values in the dictionary: for x in thisdict: print(thisdict[x]) # Or # for x in thisdict.values(): # Loop through both keys and values, by using the items() method: for x, y in thisdict.items(): print(x, y)
Copy a dictionary
You cannot copy a dictionary simply by typingdict2 = dict1
, because:dict2
will only be a reference todict1
, and changes made indict1
will automatically also be made indict2
.
Make a copy of a dictionary with the copy() method:mydict = thisdict.copy()
Create an Interator
To create an object/class as an iterator you have to implement the methods __iter__()
and __next__()
to your object.
Create an iterator that returns numbers, starting with 1, and each sequence will increase by one (returning 1,2,3,4,5 etc.):
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration
myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))
for x in myiter:
print(x)
Keywords
yield
The yield
keyword is used to create a generator function. A generator function is a special type of function that returns an iterator, which can be iterated over to produce a sequence of values. Unlike regular functions that return a single value and terminate, generator functions can yield multiple values and suspend their state, allowing them to resume execution from where they left off the next time they are called.
The yield
statement suspends a function’s execution and sends a value back to the caller, but retains enough state to enable the function to resume where it left off. When the function resumes, it continues execution immediately after the last yield run. This allows its code to produce a series of values over time, rather than computing them at once and sending them back like a list.
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
# Create a generator object
fib_gen = fibonacci(5)
# Iterate over the generator
# 0, 1, 1, 2, 3
for num in fib_gen:
print(num)
lambda
The lambda
keyword in Python is used to create anonymous functions, which are functions that don’t have a name. These functions are typically short, single-expression functions, often used as arguments to higher-order functions like map
, filter
, and sorted
.
syntax
lambda arguments: expression
example:
# A simple lambda function to add two numbers
add = lambda x, y: x + y
print(add(3, 5)) # Output: 8
use cases
In
map()
numbers = [1, 2, 3, 4] squared = map(lambda x: x ** 2, numbers) print(list(squared)) # Output: [1, 4, 9, 16]
In
filter()
numbers = [1, 2, 3, 4, 5] even_numbers = filter(lambda x: x % 2 == 0, numbers) print(list(even_numbers)) # Output: [2, 4]
In
sorted()
people = [('Alice', 25), ('Bob', 20), ('Charlie', 30)] sorted_people = sorted(people, key=lambda person: person[1]) print(sorted_people) # Output: [('Bob', 20), ('Alice', 25), ('Charlie', 30)]
In one-off calculations
result = (lambda x, y: x * y)(3, 5) print(result) # Output: 15
The post is published under CC 4.0 License.