Coding Skill cheat sheet

Strings

Remove comas from a string (or any character)

s = s.replcare(",",")

Convert string to lowercase

s = s.lower()

Loops

Iterating through a string with indices

string = "hello"
for i in range(len(string)):
	print(f'index: {i}, value: {string[i]}')

Result

index: 0, value: h
index: 1, value: e
index: 2, value: l
index: 3, value: l
index: 4, value: o

Iterating through a string directly without indexes

for char in string:
	print(char)

Iterating through a specific range

for i in range(0,10): # iterate through 0 to 10, not including 10

Dictionaries

Create a dictionary and add values

mydict = {}
mydict["val1"] = "hello"
mydict["val2"] = "world"

Compare two dictionaries

dict1 == dict2

If the dictionaries have the same keys and values, regardless of the order, the equality check will return True, This method of comparison works for dictionaries with simple values. If the dictionaries contain nested dictionaries or other complex objects, you might need to use a more sophisticated comparison approach, such as using the deepdiff library

Check if a key exists in a dictionary

exists = 'd' in dict:

Iterate through the keys and values of a dictionary

for key, value in dict.items():
	print(f'{key} : {value}')

Lists

Create a list

mylist = [1,2,3,4,5]

Accessing elements

val = mylist[0]

Slicing

sublist = my_list[1:4] # Get elements from index 1 to 3 (not including 4)

Modifying lists

my_list[0] = 10  # Change the value of the first element
my_list.append(6)  # Add an element to the end of the list
my_list.remove('four')  # Remove a specific element

Python lists come with several built-in methods for common operations:

  • append(): Add an element to the end of the list.
  • extend(): Extend the list by appending elements from another list.
  • insert(): Insert an element at a specified position.
  • remove(): Remove the first occurrence of a value.
  • pop(): Remove and return an element at a specified index.
  • index(): Return the index of the first occurrence of a value.
  • count(): Return the number of occurrences of a value.
  • sort(): Sort the list in ascending order.
  • reverse(): Reverse the order of elements in the list.

List comprehensions

squared_numbers = [x**2 for x in my_list if x%2 == 0]

Sets

Create a set

my_set = {1, 2, 3, 4, 5}      # one way
my_set = set([1, 2, 3, 4, 5]) # other way
empty_set = set()

Add a value to set

my_set.add(3)

Check if a value is in a set

exists = 3 in my_set