0 ratings0% found this document useful (0 votes) 42 views9 pagesPython Cheat Sheets
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
Python Cheat Sheet
Basic Syntax
Comments
# This is a comment
This is a
multi-line comment
Basic Input/Output
# Input
user_input = input("Enter your name.
# Output
print("Hello, "
+ user_input + "I")
)
Variables and Data Types
# Variable declaration
name = "Alice" # String
age = 30 # Integer
height = 5.7 # Float
is_student = True # Boolean
Basic Data Structures
# List
fruits = ["apple", "banana", “cherry"]
# Tuple
dimensions = (192, 1080)
# Dictionary
student = {"name": "Alice",
"2 30)
/Pythonclcoding @ /Pythoncoding EB ‘clcoding &®Python Cheat Sheet
Lists
Lists are one of the builtin data types in Python that allow you to store multiple
items in a single variable.
Creating a List
my list = [1, 2, 3, 4, 5]
Accessing Elements
first_item = my list(a] #1
last_item = my list[-1] #5
‘Adding Elements
my_list.append(6)
# Adds 6 to the end
my_list.insert(2, 0)
# Inserts @ at the beginning
Removing Elements
my_list.remove(3)
# Removes the first occurrence of 3
popped_item = my_list.pop()
# Removes and returns the last item
Slicing
sub_list = my_list[1:4]
#[2, 3, 4]
List Length
length = len(my_list)
# Gets the length of the list
Iterating Through a List
for item in my_list:
print (item)
List Comprehension
squared = [xt*2 for x in my_list]
#[@, 1, 4, 9, 16, 25, 36]
Checking for Existence
exists = 3 in my_list
# True if 3 is in my_list
Sorting a List
my_list.sort()
# Sorts the list in place
sorted_list = sorted(my_list)
# Returns a new sorted list
/Pythonclcoding @ /Pythoncoding EB /cleoding &®Python Cheat Sheet
Dictionary
Dictionaries are a builtin data type in Python that store key-value pairs. They
are unordered, mutable, and indexed by keys, allowing for fast lookups and
modifications.
Creating a Dictionary ‘Checking for Existence
my_dict = {'nane': ‘Alice’, ‘age’: 25} exists = ‘name’ in my_dict
# True if ‘name’ is a key in my dict
Accessing Values
name = my_dict[‘name'] Dictionary Length
# ‘Alice’ Length = len(my_dict)
age = my_dict.get(‘age") # Gets the nunber of key-value pairs
#25
Copying a Dictionary
‘Adding/Updating Items copy_dict = my_dict.copy()
my_dict['city'] = "New York # Creates a shallow copy of the
W Adds @ new key-value pair dictionary
my_dict[ ‘age’] = 26
# Updates the value of ‘age’
Removing Items
del my_dict[' age")
# Removes the key ‘age
value = my_dict.pop(‘city")
# Removes ‘city’ and returns its value
Iterating Through a Dictionary
for key, value in my_dict.items():
prant(f"{key}: {value}
Dictionary Comprehension
squared dict = {x: x**2 for x in range(5)}
# (0: 0, 2: 4, 2: 4, 3: 9, 4: 16}
Merging Dictionaries
another_dict = {‘city’: ‘Paris'}
merged_dict = {**my_dict, **another_dict)
# Merges to dictionaries
© /Pythonclcoding @ /Pythoncoding BB /cleoding &®Python Cheat Sheet
Sets are a built-in data type in Python that store unique elements in an
unordered collection.
Creating a Set Clearing a Set
ny_set = (1, 2,3, 4, 5) ny_set.clear()
# Removes all elements from the set
‘Adding Elements
nny_set.add(s) Iterating Through a Set
4 Adds 6 to the set for item in my_set:
print(ites
Checking Existence
exists = 2 in my_set Set Comprehension
# Thus Af 2 As An the eat squared_set = {x**2 for x in range(5)}
# (2, 1 4, 9 16)
Converting a List to a Set ] 2
ny_list = [1, 2, 2, 3, 4]
unique_set = set(my_list)
# (1, 2, 3, 4)
Set Operations
seta = (1, 2, 3)
set_b= (3, 4, 5}
Set Length
Length = Len(my_set)
# Gets the number of elements in the set
union = set_a | set_b
#(, 234 5)
intersection = set_a & set_b
# G}
difference = seta - set_b
#0, 2}
symmetric_difference = set_a * set_b
#0245)
Removing Elements
mmy_set.remove(3)
# Removes 3 from the set; raises KeyError if not found
mmy_set.discard(4)
4 Removes 4 from the set; does not raise an error if not
found
popped item = my_set.pop()
# Removes and returns an arbitrary element
/Pythonclcoding @ /Pythoncoding EW /clcoding &®Python Cheat Sheet
Tuples
Tuples are a built-in data type in Python that store ordered collections of
elements. They are immutable, meaning that once created, their elements
cannot be changed
Creating a Tuple
my_tuple = (1, 2, 3, 4, 5)
Accessing Elements
first_item = my_tuple[o]
#1
last_item = my_tuple[-1]
#5
Single-Element Tuple
single_element = (1,)
# Must include a comma
Iterating Through a Tuple
for item in my_tuple:
print (item)
Tuples are Immutable
# my_tuple[o] = 10
# Raises Typetrror
Length of a Tuple
length = len(my_tuple)
Repeating Tuples
repeated tuple = (1, 2) * 3
# (1, 2, 1, 2, 4, 2)
Packing and Unpacking
# Packing
packed = 1, 2, 3
# Unpacking
a, b, ¢ = packed
# art, 3
Slicing
sub_tuple = my_tuple[1:4]
# (2, 3, 4)
Concatenating Tuples
new_tuple = my_tuple + (6, 7)
# (1, 2, 3, 4, 5, 6, 7)
# Gets the number of elements in the tuple
/Pythonclcoding @ /Pythoncoding EB /clcoding ®Python Cheat Sheet
Range
The range function is a built-in Python function that generates a sequence of
numbers, commonly used in for-loops for iteration. It returns an immutable
sequence type, which is memory efficient for creating large ranges of numbers.
Creating a Range
= range(5)
# Creates a range object: @, 1, 2,
Converting to a List
List_range = list(range(5))
# Converts to a list: [@, 1, 2, 3,
Reverse a Range
r= range(5, @, -1)
# Creates a range object: 5, 4, 3,
Checking Membership
exists = 3 in range(5)
# True if 3 is in the range
Using with List Comprehension
squares = [x**2 for x in range(5)]
#[@, 1, 4, 9, 16)
Creating a Range Object
range(1, 10)
# Creates a range object (1, 2, 3,
Specifying Start and Stop
r= range(2, 8)
# Creates a range object: 2, 3, 4,
‘Specifying Step
r= range(®, 10, 2)
3,4 # Creates a range object: 0, 2, 4, 6, 8
Iterating Over a Range
for i in range(s):
4] print(i)
# Prints numbers from @ to 4
Length of a Range
2,1 length = len(range(5))
# Gets the length: 5
9)
5, 6,7
/Pythonclcoding @ /Pythoncoding EB clcoding a.Python Cheat Sheet
Iterators
Iterators are objects in Python that implement the iterator protocol, consisting of
the methods
-_() and _next_(). They allow you to traverse a container
(like lists, tuples, or dictionaries) without needing to access the elements by
index.
Creating an iterator
ny list = [1, 2, 3]
ny_aterstor = ster(ay_List)
# Create an iterator From a list
Using next)
First_item = next(ay_iterator)
Retrieves the first stem: 1
second_itam = next (ay_iterator)
# Retrieves the second item: 2
IRerating Using « Loop
for stem in my List:
print(item)
# prints: 1, 2, 3
Creating a Custom Iterator
class tyRange:
def _init_(self, start, end):
[Link] © start
selfiend = end
def _iter_(self)
return self
def _next_(self)
FF selfscurrent < [Link]:
result = [Link]
[Link] += 1
return result
else
raise Stoptteration
ny_range = MyRange(1, 4)
For number sn my_range
print number)
Converting to List
List_from_sterator = List(iter(range(s)))
#18) 4, 23, 4]
Checking if]an Object is an Iterator
ig Aterator = isinstance(ay iterator, iter)
Using iter) with a Function
import random
def random nunbers():
while True:
yield [Link](2, 10)
rrandom_iter = iter(random_nunbers())
for _ in range(s)
Print(next(random_iter))
fe prints random nuabers between 1 and 10
© /Pythonclcoding @ /Pythoncoding EB /cleoding &®Python Cheat Sheet
Enumerate
The enumerate function is a built-in Python function that adds a counter to an
iterable (like a list or a string) and returns it as an enumerate object. This
function is particularly useful for tracking the index of elements while iterating
through a collection.
Basic Usage Iterating Over a String
my_list = ['a', "b', 'c'] for index, char in enumerate(*hello"):
for index, value in enumerate(my_list): print(index, char)
print(index, value) # output:
# output: #oh
#oa #ie
#1b #21
#2 #31
#40
Specifying a Start Index
for index, value in enumerate(my list, starte1):
print(index, value)
# output:
tia
#2b
#3
Converting to a List of Tuples
enumerated list = list(enumerate(my_list))
# Output: [(@, 'a'), (1, 'b'), (2) 'e')]
Using with List Comprehension
enumerated_dict = {index: value for index, value in enumerate(my_list)}
# Output: {@: ‘a, 1: "b', 2: 'c"}
/Pythonclcoding @ /Pythoncoding EB /cleoding &®Python Cheat Sheet
Control Flow
Control flow refers to the order in which individual statements, instructions, or
function calls are executed or evaluated in a program.
Conditional Statements ‘Switch-Uike Structure
age = 20 def suitch_case(option):
return {
if age < 18: “option 1 selected",
print("“Hinor") "option 2 selected",
elif age < 65: 3: “Option 3 selected”
print("aduit") }.get(option, "Invalid option")
else:
print("senior") print (switch_case(2))
# Output: Option 2 selected
Nested Conditional Statements
number = 10 For Loop:
for 4 in range(5):
Af nunber > 0: print(i) # Output: 8, 1, 2, 3, 4
print("Positive
if number % 2 == 0: White Loop:
print ("even") count = 0
else: while count < 5:
print ("odd") print (count)
count += 1 # Output: 0, 1, 2, 3, 4
Breaking and Continuing Loops
for 4 in range(S):
if dee 2:
continue # Skip the number 2
print(i) # output: @, 1, 3, 4
for i in range(s):
if dae 3:
break # Exit the loop when i is 3
print(i) # output: @, 1, 2
/Pythonclcoding @ /Pythoncoding EW /cleoding &®