№8 will make you a pro-Python programmer
Credits: Wayhomestudio at Freepik.com
If you use Python every day and want to learn a few tricks that will make your code more readable then you can check out these 18 snippets below.
1. Interpolated format strings
F-strings solve the biggest problems with C-style format strings and are powerful because they allow for arbitrary Python expressions to be directly embedded within format specifiers.
val = 108
print(f'Value: {val}')
2. Prefer multiple assignments unpacking over-indexing
Readability is one of the main assets of Python and it has a special syntax called unpacking for assigning multiple values in a single statement.
dict = {'apple' " 120, 'banana': 60, 'nuts': 102} items = tuple(dict.items()) print(items) apple, banana, nuts = items #unpacking
3. Ternary operator in Python
Single-line expressions that are overly complicated to read can easily be written in Python. An If/Else expression provides a more readable alternative to using the boolean operators and in expressions.
syntax : value if true else false
4. Enumerate is the new range
If you want to iterate over an iterable and also want to fetch an iterator you can use enumerate() function. You can supply a second parameter to enumerate to specify the number from which to begin counting ( zero: default)
l = ['deku', 'bakugo', 'todoroki', 'naruto'] for indx, val in enumerate(l): print(f'Value at index {indx} is: {val}')
5. Use zip to process iterators in parallel
When iterating over multiple iterables the problem with the whole loop statement is visually noisy. Using enumerate improves this slightly, but it’s still not ideal. Zip comes to the rescue.
agents = ['Reyna', 'Jett', 'Viper'] kills = [13, 2, 14] for agent, kill in zip(agents, kills): print(f'Agent {agent} : Kills {kill}')
6. Use the new walrus operator
Many times we programmers see this pattern of fetching a value, checking to see if it’s non-zero, and then using it. This makes it difficult to maintain Python’s core feature when writing programs ie readability. Thus, in Python 3.8 walrus operator was added to streamline exactly this type of code.
if killCount := mostKills('Jett', 0) killFeed(killCount) else: print('Jett noob')
7. Know how to slice your sequences
Slicing on the cake and slicing syntax in Python are true to their nature. Slicing allows you to access a subset of a sequence’s items with minimal effort.
l = [1, 2, 3, 4, 5, 6] syntax : l[start:end]
l[:] # all elements l[:3] # start at 0 and end at 3rd element l[3:] # start from 3rd element and end at last
use negative slicing l[:-1] # all elements except 6 (ie last) l[2:-1] # start from 2nd element and end and remove last element
8. Know when to use slicing and indexing
You can rely on indexing and slicing but many times you will be unaware of the size of the iterable, that time you will run into a runtime error. The best way to solve this is to use starred expressions.
first, *middleIDK, last = [1, 2, 3, 4, 5]
first # 1 middleIDK # 2, 3, 4 last # 5
9. Convert any class into a dictionary
Classes have an inbuilt attribute __dict__ which means objects that are created are dictionaries and can be used like one when needed.
class Obj: def __init__(self, a = 'test', b = 108): self.a = a self.b = b obj = Obj() print(vars(obj)) # vars() is pythonic way to convert to dictionary
10. Handle missing dictionary keys using get
If you generally use ‘in’ to check if a key is present in the dictionary then you are missing out on a better option that is available to you.
You can use the setdefault method to fetch the value of a key, if it’s not present the method assigns that key to the default value provided.
agents = leaderboard.setdefault(key, [])
You should ideally try not to use this since it will create a default value for every key not found and can lead to performance overhead.
However, if you want a better approach for readability you can use the get method along with a walrus operator like this.
if (agents := ) is None: leaderboad[key] = agents = []