0% found this document useful (0 votes)
8 views

Srinivas Ram Cheat Sheet for Python Topics

This cheat sheet provides a concise overview of essential Python topics, including lists, tuples, dictionaries, and strings. It covers definitions, methods, and examples for each data structure, highlighting their characteristics and advantages. The document serves as a quick reference for Python programming concepts and syntax.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Srinivas Ram Cheat Sheet for Python Topics

This cheat sheet provides a concise overview of essential Python topics, including lists, tuples, dictionaries, and strings. It covers definitions, methods, and examples for each data structure, highlighting their characteristics and advantages. The document serves as a quick reference for Python programming concepts and syntax.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Cheat sheet for Python Topics Cheat Sheet

by srinivas.ram via cheatography.com/183208/cs/38151/

Python Lists Python Lists (cont) Python Lists (cont)

#Defin​ition: Elements in a list can be modified using # Using sort() method :


A list is a mutable collection of ordered indexing or slicing. my_lis​t.s​ort()
elements enclosed in square brackets []. my_list = [1, 2, 3] print(my_list)
Lists can contain any type of data, including my_list[0] = 4 # Output: [0, 1, 4, 5, 6]
other lists. print(​my_​list) # Output: [4, 2, 3]
# Using reverse() method :
#Creating a List : Some Examples to modify elements using
my_lis​t.r​eve​rse()
index and slice()
Lists can be created using square brackets print(my_list)
[] or the list() constr​uctor. my_list = ['apple', 'banana', 'cherry'] # Output: [6, 5, 4, 1, 0]
my_list[1] = 'orange' changes the second
#Using Square brackets: Copying a List:
element in the list to 'orange'.
my_list = [1, 2, 3] my_list = ['apple', 'banana', 'cherry']
my_lis​t.a​ppe​nd(​'gr​ape') adds 'grape' to the
# Using the list () constr​uctor: new_list = my_lis​t.c​opy()
end of the list.
my_list = list([1, 2, 3]) my_lis​t.e​xte​nd(​['k​iwi', 'water​mel​on']) adds Nested Lists:

myList = list(r​ang​e(5)) # a list with five items the list ['kiwi', 'water​melon'] to the end of the my_list = [[1, 2], [3, 4]]
[0, 1, 2, 3, 4] list. print(my_list[0][1]) # Output: 2
myList = [i*2 for i in range(5)] a list with five my_lis​t.r​emo​ve(​'ch​erry') removes the
List Functions:
items [0, 2, 4, 6, 8] element 'cherry' from the list.
sum(my​_list)
my_lis​t.p​op(0) removes and returns the first
Accessing Elements : all(my_list)
element in the list ('apple').
Elements in a list can be accessed using any(my_list)
List Methods :
indexing or slicing. enumerate(my_list)
Lists have many built-in methods, including: zip(my_list1, my_list2)
# Accessing an element using indexing :
# Using append() method : List Compre​hen​sions :
my_list = [1, 2, 3, 4, 5]
Print(my_list[0]) # output: 1 accesses the my_list = [1, 2, 3] List compre​hen​sions provide a concise way
first element in the list (1). my_list.append(4) to create lists based on existing lists.
print(my_list)
# Accessing a slice of elements using # Creating a new list using list compre​‐
# Output: [1, 2, 3, 4]
slicing : hension :
# Using extend() method :
print(​my_​lis​t[1​:4])) # Output: [2, 3, 4] my_list = [1, 2, 3, 4, 5]
my_lis​t.e​xte​nd([5, 6]) new_list = [x * 2 for x in my_list]
Some examples on indexing and slicing :
print(my_list) print(new_list) # Output: [2, 4, 6, 8, 10]
my_list = ['apple', 'banana', 'cherry']
# Output: [1, 2, 3, 4, 5, 6] my_list = [x for x in range(1, 6)]
print(my_list[1]) # Output: banana accesses
# Using insert() method : even_list = [x for x in range(1, 11) if x % 2
the second element in the list ('bana​na').
== 0]
print(my_list[-1]) # Output: cherry accesses my_lis​t.i​nse​rt(0, 0)
the last element in the list ('cher​ry'). print(my_list) Advantage of Using Lists :
print(my_list[1:]) # Output: ['banana', # Output: [0, 1, 2, 3, 4, 5, 6] Lists are mutable, which makes them more
'cherry'] accesses all elements in the list # Using remove() method : flexible to use than tuples.
from the second element to the end
my_lis​t.r​emo​ve(3)
Modifying Elements : 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]

By srinivas.ram Not published yet. Sponsored by ApolloPad.com


cheatography.com/srinivas- Last updated 9th April, 2023. Everyone has a novel in them. Finish
ram/ Page 1 of 3. Yours!
https://apollopad.com
Cheat sheet for Python Topics Cheat Sheet
by srinivas.ram via cheatography.com/183208/cs/38151/

Tuples In Python Tuples In Python (cont) Dictio​naries in Python (cont)

What are Tuples? Returns the number of times a specified # Accessing a value by key
A tuple is an ordered, immutable collection value occurs in a tuple. my_dict["key1"] # returns "value1"
of elements. my_tuple = (1, 2, 2, 3, 2, 4) # Using the get() method to avoid KeyError
In Python, tuples are created using parent​‐ # Count the number of times the value 2 my_dict.get("key1") # returns "value1"
heses () appears my_dict.get("key4") # returns None
and the elements are separated by commas print(my_tuple.count(2)) # Output: 3 # Using the get() method with a default
,. index() value
my_dict.get("key4", "​def​aul​t_v​alu​e") #
Creating Tuples Returns the index of the first occurrence of a
returns "​def​aul​t_v​alu​e"
# Create an empty tuple specified value in a tuple.
my_tuple = (1, 2, 2, 3, 2, 4) Adding and updating values
my_tuple = ()
# Create a tuple with elements # Find the index of the first occurrence of # Adding a new key-value pair

my_tuple = (1, 2, 3) the value 3 my_dict["key4"] = "value4"


# Create a tuple with a single element print(my_tuple.index(3)) # Output: 3 # Updating a value
my_tuple = (1,) Tuple Unpacking my_dict["key1"] = "new_value1"
# Create a tuple without parentheses # Using the update() method to add/update
You can also "​unp​ack​" tuples, which allows
my_tuple = 1, 2, 3 multiple values
you to assign the values in a tuple to
my_dict.update({"key5": "​val​ue5​", "​key​6": "​‐
Accessing Elements separate variables.
val​ue6​"})
Tuples are ordered collec​tions, my_tuple = ('John', 'Doe', 30)
# Unpack the tuple into separate variables Removing values
So you can access individual elements
using indexing. first_name, last_name, age = my_tuple # Removing a key-value pair
my_tuple = ('apple', 'banana', 'cherry') print(first_name) # Output: 'John' del my_dict["key1"]
print(last_name) # Output: 'Doe' # Using the pop() method to remove a key-
# Access the first element
print(age) # Output: 30 value pair and return the valmy_​dic​t.p​op(​"​‐
print(​my_​tup​le[0]) # Output: 'apple'
Advantages of Tuples key​2") # returns "value2"ue
# Access the last element
Tuples are immutable, so they're useful for
print(​my_​tup​le[-1]) # Output: 'cherry' # Using the pop() method with a default
storing data that shouldn't be changed
value
Immuta​bility accidentally.
my_dict.pop("key4", "​def​aul​t_v​alu​e") #
Tuples are immutable, which means that Tuples are faster than lists, since they're
returns "default_value"
you can't modify their contents after they're smaller and can be stored more effici​ently
# Using the clear() method to remove all
created. in memory.
key-value pairs
my_tuple = (1, 2, 3) Tuples can be used as dictionary keys,
my_dict.clear()
# Trying to modify the first element will while lists cannot.
Other methods
result in an error
my_tuple[0] = 4 # TypeError: 'tuple' object Dictio​naries in Python # Getting the number of key-value pairs
does not support item assignment len(my_dict)
Creating a dictionary
# Checking if a key exists in the dictionary
Tuple Methods # Empty dictionary
"key1" in my_dict
Tuples have a few built-in methods that you my_dict = {}
# Getting a list of keys
can use: # Dictionary with initial values
my_dict.keys()
count() my_dict = {"ke​y1": "​val​ue1​", "​key​2": "​val​‐
# Getting a list of values
ue2​", "​key​3": "value3"}
my_dict.values()
# Using the dict() constructor
# Getting a list of key-value pairs as tuples
my_dict = dict(k​ey1​="va​lue​1", key2="v​alu​‐
my_dict.items()
e2", key3="v​alu​e3")
Advantages of Python dictio​naries
Accessing values

By srinivas.ram Not published yet. Sponsored by ApolloPad.com


cheatography.com/srinivas- Last updated 9th April, 2023. Everyone has a novel in them. Finish
ram/ Page 2 of 3. Yours!
https://apollopad.com
Cheat sheet for Python Topics Cheat Sheet
by srinivas.ram via cheatography.com/183208/cs/38151/

Dictio​naries in Python (cont) Python strings (cont)

Python dictio​naries offer fast lookups, name = "John"


flexible key/value storage, age = 30
dynamic resizing, efficient memory usage, print("My name is {} and I'm {} years old".fo​‐
and ease of use, making them a versatile rma​t(name, age))
and powerful data structure widely used in # My name is John and I'm 30 years old
Python progra​mming. # f-strings (Python 3.6+)
print(f"My name is {name} and I'm {age}
Python strings years old")
# My name is John and I'm 30 years old
Creating strings
Encoding and decoding strings
my_string = "​Hello, World!​" # double quotes
my_string = 'Hello, World!' # single quotes my_string = "​Hello, World!"
my_string = "​"​"​Hello, World!​"​"​" # triple encoded_string = my_str​ing.en​cod​e("u​tf-​8")
quotes (for multiline strings) # b'Hello, World!'
decoded_string = encode​d_s​tri​ng.d​ec​ode​‐
Accessing characters in a string
("ut​f-8​") # Hello, World!
my_string = "​Hello, World!"
Advantages of strings in Python
print(my_string[0]) # H
print(my_string[-1]) # ! Strings in Python have several advant​ages,
including their flexibility,
Slicing strings
ease of use, and extensive library of built-in
my_string = "​Hello, World!"
string methods,
print(my_string[0:5]) # Hello
making it easy to manipulate and format
print(my_string[7:]) # World!
text data for various purposes
print(my_string[:5]) # Hello
such as data analysis, web develo​pment,
print(my_string[::2]) # Hlo ol!
and automation tasks.
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

By srinivas.ram Not published yet. Sponsored by ApolloPad.com


cheatography.com/srinivas- Last updated 9th April, 2023. Everyone has a novel in them. Finish
ram/ Page 3 of 3. Yours!
https://apollopad.com

You might also like