Basic Tips - Intermediate Tips - Advanced Tips
## Basic Tips ### 1) Learn how to iterate properly - Use ```for index, item in enumerate(list):``` to loop over the ```index``` of an item and the ```item``` at the same time. - Use ```for key, value in dictn.items():``` instead of iterating over ```keys``` and then getting values as ```dictn[key]```. - Use ```for item1, item2 in zip(list1, list2):``` to iterate over two lists at a time.| Instead of doing this... | try this: |
|---|---|
| ```python file = open(file_path, 'w') file.write('Hello, World!') file.close() ``` | ```python with open(file_path, 'w') as file: file.write('Hello, World!') # The file is closed automatically. ``` |
| Instead of doing this... | try this: |
|---|---|
| ```python name = input('Enter your name: ') surname = input('Enter your surname: ') print('Hello, ' + name + ' ' + surname) ``` | ```python name = input('Enter your name: ') surname = input('Enter your surname: ') print(f'Hello, {name} {surname}') ``` |
| Instead of doing this... | try this: |
|---|---|
| ```python names = ['Olivia', 'Nicholas', 'Violet'] text = '' for name in names: text += name + ', ' text = text[:-2] print(text) # >> 'Olivia, Nicholas, Violet' ``` | ```python names = ['Olivia', 'Nicholas', 'Violet'] text = ', '.join(names) print(text) # >> 'Olivia, Nicholas, Violet' ``` |
| Instead of doing this... | try this: |
|---|---|
| ```python cities = ['London', 'Paris', 'London'] unique_cities = [] for city in cities: if city not in unique_cities: unique_cities.append(city) print(unique_cities) # >> ['London', 'Paris'] ``` | ```python cities = ['London', 'Paris', 'London'] unique_cities = set(cities) print(unique_cities) # >> {'London', 'Paris'} unique_cities = list(unique_cities) print(unique_cities) # >> ['London', 'Paris'] ``` |
| Instead of doing this... | try this: |
|---|---|
| ```python if variable == a or variable == b: res = do_something(variable) ``` | ```python if variable in {a, b}: res = do_something(variable) ``` |
| This code... | is equivalent to this code: |
|---|---|
| ```python if b > 10: a = 0 else: a = 5 ``` | ```python a = 0 if b > 10 else 5 ``` |
| Instead of doing this... | try this: |
|---|---|
| ```python if data: lst = data else: lst = [0, 0, 0] ``` | ```python lst = data or [0, 0, 0] ``` |
| Instead of doing this... | try this: |
|---|---|
| ```python if not os.path.isfile(filename): print('File does not exist.') if not os.access(filename, os.W_OK): print('You dont have write permission.') with open(filename, 'w') as file: file.write('Hello, World!') ``` | ```python try: with open(filename, 'w') as file: file.write('Hello, World!') except FileNotFoundError: print('File does not exist.') except PermissionError: print('You dont have write permission.') except OSError as exc: print(f'An OSError has occurred:\n{exc}') ``` |
| Instead of doing this... | try this: |
|---|---|
| ```python text = "Hello, World" length = 20 text = " "*((length//2) - (len(text)//2)) \ + text \ + " "*((length//2) - (len(text)//2)) print(text) # >> " Hello, World " ``` | ```python text = "Hello, World" length = 20 text = text.center(length) print(text) # >> " Hello, World " ``` |
| Instead of doing this... | try this: |
|---|---|
| ```python items = [item1, item2, item3, item4...] new_items = [] for item in items: item = do_something(item) # Extract item = do_smth_else(item) # this ... # logic. new_items.append(item) ``` | ```python items = [item1, item2, item3, item4...] def process_item(item): # 'process_item' item = do_something(item) # now does the item = do_smth_else(item) # processing ... # for a single return item # item. new_items = [process_item(item) for item in items] ``` |
| Instead of doing this... |
|---|
| ```python comments = {line_idx: line.strip() for line_idx, line in enumerate(file) if line.startswith('#')} ``` |
| try this: |
|---|
| ```python comments = {line_idx: line.strip() for line_idx, line in enumerate(file) if line.startswith('#')} ``` |
| Instead of doing this... | try this: |
|---|---|
| ```python numbers = [1, 3, 4, 5, 7, 9, 2] sum = 0 for number in numbers: sum += number avg = sum / len(numbers) ``` | ```python from numpy import mean numbers = [1, 3, 4, 5, 7, 9, 2] avg = mean(numbers) ``` |
| Instead of doing this... | try this: |
|---|---|
| ```python requests = [req1, req2...] results = [] for request in requests: res = process_request(request) results.append(res) # Runs in 1m 22s, depending on HW. ``` | ```python from multiprocessing import Pool requests = [req1, req2...] with Pool as p: results = p.map(process_request, requests) # Runs in 16s, depending on HW. ``` |
| Instead of doing this... | try this: |
|---|---|
| ```python numbers = [1, 3, 4, 5, 7, 9, 2] result = None for number in numbers: if number > 3: result = number break print(result) # >> 4 ``` | ```python numbers = [1, 3, 4, 5, 7, 9, 2] result = next((number for number in numbers if number > 3), None) # Fallback value. print(result) # >> 4 ``` |