Cheat sheet for Python Topics Cheat Sheet
by srinivas.ram via cheatography.com/183208/cs/38151/
Python Lists Python Lists (cont) Python Lists (cont)
#Definition: Elements in a list can be modified using # Using sort() method :
A list is a mutable collection of ordered indexing or slicing. my_list.sort()
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_list.reverse()
index and slice()
Lists can be created using square brackets print(my_list)
[] or the list() constructor. 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_list.append('grape') adds 'grape' to the
# Using the list () constructor: new_list = my_list.copy()
end of the list.
my_list = list([1, 2, 3]) my_list.extend(['kiwi', 'watermelon']) adds Nested Lists:
myList = list(range(5)) # a list with five items the list ['kiwi', 'watermelon'] 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_list.remove('cherry') removes the
List Functions:
items [0, 2, 4, 6, 8] element 'cherry' from the list.
sum(my_list)
my_list.pop(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 Comprehensions :
my_list = [1, 2, 3, 4, 5]
Print(my_list[0]) # output: 1 accesses the my_list = [1, 2, 3] List comprehensions 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_list[1:4])) # Output: [2, 3, 4] my_list = [1, 2, 3, 4, 5]
my_list.extend([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 ('banana').
== 0]
print(my_list[-1]) # Output: cherry accesses my_list.insert(0, 0)
the last element in the list ('cherry'). 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_list.remove(3)
Modifying Elements : print(my_list)
# Output: [0, 1, 2, 4, 5, 6]
# Using pop() method :
my_list.pop(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) Dictionaries 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", "default_value") #
Creating Tuples Returns the index of the first occurrence of a
returns "default_value"
# 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 "unpack" tuples, which allows
my_tuple = 1, 2, 3 multiple values
you to assign the values in a tuple to
my_dict.update({"key5": "value5", "key6": "‐
Accessing Elements separate variables.
value6"})
Tuples are ordered collections, 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_dict.pop("‐
print(my_tuple[0]) # Output: 'apple'
Advantages of Tuples key2") # returns "value2"ue
# Access the last element
Tuples are immutable, so they're useful for
print(my_tuple[-1]) # Output: 'cherry' # Using the pop() method with a default
storing data that shouldn't be changed
value
Immutability accidentally.
my_dict.pop("key4", "default_value") #
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 efficiently
# 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 Dictionaries 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 = {"key1": "value1", "key2": "val‐
# Getting a list of values
ue2", "key3": "value3"}
my_dict.values()
# Using the dict() constructor
# Getting a list of key-value pairs as tuples
my_dict = dict(key1="value1", key2="valu‐
my_dict.items()
e2", key3="value3")
Advantages of Python dictionaries
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/
Dictionaries in Python (cont) Python strings (cont)
Python dictionaries 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 rmat(name, age))
and powerful data structure widely used in # My name is John and I'm 30 years old
Python programming. # 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_string.encode("utf-8")
quotes (for multiline strings) # b'Hello, World!'
decoded_string = encoded_string.decode‐
Accessing characters in a string
("utf-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 advantages,
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 development,
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)
Concatenating 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