Python Basics Cheatsheet

Basics Cheatsheet

This cheat sheet contains only the most used types, operations, methods, etc., of core Python programming, just the basics.

Comments

# This is a comment

Variables

x = 10
x, y = 10, 20

Global Variable

x = 'hello world'
def myfunc():
  global x
  print(x)

Datatypes

str

x = "Hello World"

int

x = 20

float

x = 20.5

bool

x = True

Type casting

x = int(3.14)
x = float("3.14")
x = str(3.14)

Strings

x = "hello world"

multiline string

x = '''hello
world'''

access character using index

x[2] #returns char at index=2

string length

len(x)

concatenate strings

x = "hello" + "world"

count no. of occurrences of “apple” in x

x.count("apple") #returns int

if string ends with “le”

x.endswith("le") #returns bool

find index of ‘apple’ in x

x.find("apple") #returns int
x.index("apple")

format string

x = "apple - {price:.2f}"
print(x.format(price = 49.1245))

convert to lowercase, uppercase

x.lower()
x.upper()

replace “apple” with “cherry”

x.replace("apple", "cherry")

split string by separator “-“

x.split("-")

trim whitespaces

x.strip()

Lists

x = ["apple", "banana", "cherry"]

access item using index

value = x[2]
x[2] = "mango"

length of list x

len(x)

list slicing

# Read
x[1:4]

# Update
x[1:2] = ["ab", "cd"]

if item “apple” in list x

if "apple" in x:
    print("item is in list")

iterate over list x with For loop

for item in x:
    print(item)

list comprehension

newlist = [item for item in x]

# With two lists
[(ix, iy) for ix in x for iy in y]

append item

x.append("mango")

append a list x with another list y

x.extend(y)

join lists

z = x + y

sorting

x.sort() #ascending

reverse list

x.reverse()

remove all items in list

x.clear()

remove an item by value

x.remove("cherry")

remove an item at index 2

x.pop(2)

Sets

x = {"apple", "banana", "cherry"}

if item “apple” in set x

if "apple" in x:
    print("item is in set")

iterate over set x with For loop

for item in x:
    print(item)

add item

x.add("mango")

return union of two sets

x.union(y)

return intersection of two sets

x.intersection(y)

update this set with the union of the two sets

x.update(y)

remove an item by value

x.remove("cherry")

remove and return an item from set

x.pop()

remove all items in set

x.clear()

Dictionaries

x = {"apple": 10, "banana": 20)

iterate over keys of dictionary x

for key in x:
    print(key)

iterate over values of dictionary x

for value in x.values():
    print(key)

iterate over (key, value) of dictionary x

for key, value in x.items():
    print(key, value)

update value for a specific key k in dictionary x

x[k] = new_value

Tuples

x = ("apple", "banana", "cherry")

if item “apple” in tuple x

if "apple" in x:
    print("item is in tuple")

iterate over tuple x with For loop

for item in x:
    print(item)

unpack tuples

x = ("apple", "banana", "cherry")
(a, b, c) = x
print(a) #apple

Code copied to clipboard successfully 👍