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 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()
The post is published under CC 4.0 License.