DEV Community

Cover image for Python DSA Cheat-sheet for SuperHeros
jeetvora331
jeetvora331

Posted on

Python DSA Cheat-sheet for SuperHeros

Here is a python cheat sheet that can be useful in solving data structure and algorithm problems. It covers some of the basic and intermediate operations on lists, tuples, dictionaries and sets, as well as some common algorithms and their complexities. I hope you find it helpful.

Image description

# Python Cheat Sheet for Data Structures and Algorithms

# List and Tuple Operations

# Creating a list or tuple
my_list = [1, 2, 3, 4] # use square brackets for lists
my_tuple = (5, 6, 7, 8) # use parentheses for tuples

# Accessing elements by index
first = my_list[0] # get the first element of the list (index 0)
last = my_tuple[-1] # get the last element of the tuple (index -1)

# Slicing a list or tuple
sublist = my_list[1:3] # get a sublist from index 1 (inclusive) to index 3 (exclusive)
subtuple = my_tuple[:2] # get a subtuple from the beginning to index 2 (exclusive)
reversed_list = my_list[::-1] # get a reversed list using negative step

# Concatenating two lists or tuples
new_list = my_list + [9, 10] # create a new list by adding another list
new_tuple = my_tuple + (11, 12) # create a new tuple by adding another tuple

# Repeating a list or tuple
repeated_list = my_list * 2 # create a new list by repeating the original list twice
repeated_tuple = my_tuple * 3 # create a new tuple by repeating the original tuple three times

# Checking membership of an element
is_in_list = 3 in my_list # returns True if 3 is in the list, False otherwise
is_in_tuple = 9 in my_tuple # returns False if 9 is not in the tuple, True otherwise

# Iterating over a list or tuple
for x in my_list: # loop through each element x in the list
    print(x) # print x

for i, x in enumerate(my_tuple): # loop through each index i and element x in the tuple
    print(i, x) # print i and x

# Unpacking a list or tuple
a, b, c, d = my_list # assign each element of the list to a variable
e, f, g, h = my_tuple # assign each element of the tuple to a variable
Enter fullscreen mode Exit fullscreen mode

List Methods

# List methods (do not apply to tuples)
my_list.append(5) # add an element 5 at the end of the list
my_list.insert(2, 6) # insert an element 6 at index 2 of the list
my_list.remove(4) # remove the first occurrence of element 4 from the list
my_list.pop() # remove and return the last element of the list
my_list.pop(1) # remove and return the element at index 1 of the list
my_list.index(3) # return the index of the first occurrence of element 3 in the list
my_list.count(2) # return the number of times element 2 appears in the list
my_list.sort() # sort the list in ascending order (modify the original list)
my_list.reverse() # reverse the order of the list (modify the original list)
my_list.copy() # return a shallow copy of the list
my_list.clear() # remove all elements from the list
Enter fullscreen mode Exit fullscreen mode

Dictionary Operations

  • Dictionaries are unordered collections of key-value pairs that do not allow duplicate keys
  • Dictionaries are mutable (can be changed) and support indexing by key, membership testing by key,
  • Iteration by key or value or item, and unpacking into variables
# Creating a dictionary
my_dict = {"name": "Alice", "age": 25, "gender": "female"} # use curly braces and colons for dictionaries

# Accessing values by keys
name = my_dict["name"] # get the value associated with the key "name"
age = my_dict.get("age") # get the value associated with the key "age" or None if not found

# Adding or updating key-value pairs
my_dict["email"] = "alice@gmail.com" # add a new key-value pair to the dictionary
my_dict["age"] = 26 # update the value associated with the key "age"

# Removing key-value pairs
del my_dict["gender"] # delete the key-value pair with the key "gender" from the dictionary
email = my_dict.pop("email") # remove and return the value associated with the key "email"
name, age = my_dict.popitem() # remove and return an arbitrary key-value pair as a tuple

# Checking membership of a key
is_in_dict = "name" in my_dict # returns True if "name" is a key in the dictionary, False otherwise

# Iterating over a dictionary
for key in my_dict: # loop through each key in the dictionary
    print(key) # print key

for value in my_dict.values(): # loop through each value in the dictionary
    print(value) # print value

for key, value in my_dict.items(): # loop through each key-value pair in the dictionary
    print(key, value) # print key and value

# Unpacking a dictionary into variables
name, age, gender = my_dict # assign each key of the dictionary to a variable
{"name": name, "age": age, "gender": gender} = my_dict # assign each value of the dictionary to a variable
Enter fullscreen mode Exit fullscreen mode

Dictionary methods

my_dict.keys() # return a view object of the keys of the dictionary
my_dict.values() # return a view object of the values of the dictionary
my_dict.items() # return a view object of the key-value pairs of the dictionary
my_dict.update({"city": "New York", "age": 27}) # update the dictionary with another dictionary or iterable
my_dict.copy() # return a shallow copy of the dictionary
my_dict.clear() # remove all key-value pairs from the dictionary
Enter fullscreen mode Exit fullscreen mode

Set Operations

  • Sets are unordered collections of elements that do not allow duplicates
  • Sets are mutable (can be changed) and support membership testing, iteration, and mathematical set operations

# Creating a set
my_set = {1, 2, 3, 4} # use curly braces for sets (but no colons)
empty_set = set() # use the set() function to create an empty set

# Adding or removing elements
my_set.add(5) # add an element 5 to the set
my_set.remove(4) # remove an element 4 from the set (raises KeyError if not found)
my_set.discard(3) # remove an element 3 from the set (does nothing if not found)
my_set.pop() # remove and return an arbitrary element from the set (raises KeyError if empty)
my_set.clear() # remove all elements from the set

# Checking membership of an element
is_in_set = 2 in my_set # returns True if 2 is in the set, False otherwise

# Iterating over a set
for x in my_set: # loop through each element x in the set
    print(x) # print x
Enter fullscreen mode Exit fullscreen mode

String Methods

These string methods can be helpful in solving various string manipulation problems that you may encounter in Data Structure and Algorithm problems on platforms like LeetCode.

my_string = "   Hello, World!   "

# Length of a string
length = len(my_string)
print(length)  # Output: 19

# Splitting a string into a list
my_list = my_string.split(" ")
print(my_list)  # Output: ['', '', '', 'Hello,', 'World!', '', '', '']

# Joining elements of a list into a string
my_string = " ".join(my_list)
print(my_string)  # Output:    Hello, World!

# Checking if a substring exists in a string
if "Hello" in my_string:
    print("Substring found!")  # Output: Substring found!

# Replacing occurrences of a substring
new_string = my_string.replace("World", "Python")
print(new_string)  # Output:    Hello, Python!

# Converting a string to lowercase/uppercase
lowercase = my_string.lower()
uppercase = my_string.upper()
print(lowercase)  # Output:    hello, world!
print(uppercase)  # Output:    HELLO, WORLD!

# Checking if a string starts/ends with a specific substring
starts_with_hello = my_string.startswith("Hello")
ends_with_exclamation = my_string.endswith("!")
print(starts_with_hello)  # Output: False
print(ends_with_exclamation)  # Output: True

# Removing leading/trailing whitespace from a string
stripped_string = my_string.strip()
print(stripped_string)  # Output: Hello, World!

# Checking if a string is alphanumeric
is_alphanumeric = my_string.isalnum()
print(is_alphanumeric)  # Output: False

# Counting occurrences of a substring
count = my_string.count("Hello")
print(count)  # Output: 1

Enter fullscreen mode Exit fullscreen mode

Top comments (0)