20 Python Concepts I Wish I Knew Way Earlier - by Liu Zuo Lin - Apr, 2023 - Level Up Coding
20 Python Concepts I Wish I Knew Way Earlier - by Liu Zuo Lin - Apr, 2023 - Level Up Coding
You have 1 free member-only story left this month. Sign up for Medium and get an extra one.
Member-only story
Listen Share
https://levelup.gitconnected.com/20-python-concepts-i-wish-i-knew-way-earlier-573cd189c183 1/24
5/26/23, 2:56 PM 20 Python Concepts I Wish I Knew Way Earlier | by Liu Zuo Lin | Apr, 2023 | Level Up Coding
There are lots of concepts we need to grasp in Python. And everyone learns them
differently, in different sequences. Here are some things I wish I learnt much earlier
when I was still a Python beginner.
# first='apple', second='orange'
# others = ['pear', 'pineapple', 'durian', 'banana']
^ we can add * in front of variables to unpack everything else into that variable.
https://levelup.gitconnected.com/20-python-concepts-i-wish-i-knew-way-earlier-573cd189c183 2/24
5/26/23, 2:56 PM 20 Python Concepts I Wish I Knew Way Earlier | by Liu Zuo Lin | Apr, 2023 | Level Up Coding
^ with list comprehension, we can create a custom list in one line of code.
^ set comprehension and dictionary comprehension can be used to create sets and
dictionaries in the same way we create lists using list comprehensions.
3) Ternary operator
score = 57
if score > 90:
grade = 'A*'
elif score > 50:
grade = 'pass'
else:
grade = 'fail'
# grade = 'pass'
score = 57
grade = 'A*' if score>90 else 'pass' if score>50 else 'fail'
# grade = 'pass'
^ we can condense the if-elif-else block into ONE line using the ternary operator.
https://levelup.gitconnected.com/20-python-concepts-i-wish-i-knew-way-earlier-573cd189c183 3/24
5/26/23, 2:56 PM 20 Python Concepts I Wish I Knew Way Earlier | by Liu Zuo Lin | Apr, 2023 | Level Up Coding
class Dog():
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f'Dog(name={self.name}, age={self.age})'
^ apart from __init__ , __str__ and __gt__ are magic methods that allow us to do
special things with our Dog objects.
dog = Dog('rocky', 4)
print(dog) # Dog(name=rocky, age=4)
^ the __str__ magic method defines what is returned when we call str(dog) , which is
called when we print the dog object.
dog1 = Dog('rocky', 4)
dog2 = Dog('fifi', 2)
^ the __gt__ magic method defines what happens when we compare 2 dogs using the
> operator.
https://levelup.gitconnected.com/20-python-concepts-i-wish-i-knew-way-earlier-573cd189c183 4/24
5/26/23, 2:56 PM 20 Python Concepts I Wish I Knew Way Earlier | by Liu Zuo Lin | Apr, 2023 | Level Up Coding
^ *args allow our functions to take in any number of positional arguments (which will
be stored in a tuple args )
^ **kwargs allow our functions to take in any number of keyword arguments (which
will be stored in a dict kwargs )
# helper.py
def test123():
print('test123 is called')
# main.py
from helper import test123
When you get a job as a software engineer, you WILL work on projects with many
many many different files. Do get familiar early with how to import functions from
other files.
https://levelup.gitconnected.com/20-python-concepts-i-wish-i-knew-way-earlier-573cd189c183 5/24
5/26/23, 2:56 PM 20 Python Concepts I Wish I Knew Way Earlier | by Liu Zuo Lin | Apr, 2023 | Level Up Coding
7) if __name__ == ‘__main__’
# helper.py
def test123():
print('test123 is called')
if __name__ == '__main__':
# this line only runs if we run helper.py DIRECTLY
print('print statement from helper.py')
# main.py
from helper import *
^ the line if __name__ == '__main__' evaluates to True in a .py file only if we run the .py
file directly. We use this line so that we don’t accidentally run lines of code that we
don’t intend to run.
for i in [1,2,3,4,5]:
if i == 3:
break
print(i)
for i in [1,2,3,4,5]:
if i == 3:
continue
print(i)
https://levelup.gitconnected.com/20-python-concepts-i-wish-i-knew-way-earlier-573cd189c183 7/24
5/26/23, 2:56 PM 20 Python Concepts I Wish I Knew Way Earlier | by Liu Zuo Lin | Apr, 2023 | Level Up Coding
for i in [1,2,3,4,5]:
if i == 3:
pass
print(i)
try:
# risky code that could cause exceptions
except:
# this block executes if an exception happens in the try block
finally:
# stuff here will ALWAYS execute
^ try-except-finally blocks allow us to handle stuff when errors and exceptions happen
in our code (instead of just crashing)
https://levelup.gitconnected.com/20-python-concepts-i-wish-i-knew-way-earlier-573cd189c183 8/24
5/26/23, 2:56 PM 20 Python Concepts I Wish I Knew Way Earlier | by Liu Zuo Lin | Apr, 2023 | Level Up Coding
Python Flask — we can build APIs using Flask too, and even simple web
applications
12) Decorators
I learnt about this VERY late in my Python journey, and used to ignore any @decorator
syntax that I saw. But it’s better to understand what’s happening in your code.
def add_exclamation_mark(your_function):
def inner(*args, **kwargs):
return your_function(*args, **kwargs)
return inner
@add_exclamation_mark
def greet(name):
return f'hello {name}'
Decorators are functions that 1) take in another function 2) tweak how the functio
works and 3) return another function. When we put @add_exclamation_mark above the
greet function, we are actually decorating the greet function, and changing how the
greet function works.
# @add_exclamation_mark
# def greet(name)
#
# ^ THIS IS THE SAME AS BELOW:
#
# greet = add_exclamation_mark(greet)
^ what happens when we call the decorated greet function. Due to our decorator, our
greet function behaves differently, and now has an additional ! after its returned
value.
def simple_generator():
yield 'apple'
yield 'orange'
yield 'pear'
The yield keyword is like the return keyword. Except that the function does not stop
completely after yielding something.
A function that contains the yield keyword becomes a generator function, and can
have multiple outputs (the stuff that are yielded).
^ we can chain multiple methods together in one line to save ourselves a few lines of
code.
https://levelup.gitconnected.com/20-python-concepts-i-wish-i-knew-way-earlier-573cd189c183 10/24
5/26/23, 2:56 PM 20 Python Concepts I Wish I Knew Way Earlier | by Liu Zuo Lin | Apr, 2023 | Level Up Coding
After I learnt how machine learning worked (on a basic level), I was like oh ok so it’s
kinda automated statistics with help from a computer. It was no longer magical magic.
Machine learning is a huge huge field, but we usually start with supervised learning —
more specifically, classification and regression. As a starter kit, do check out scikit-
learn , a Python library that does all the machine learning code for you, and allows you
to simply use their functions and classes.
If you’re interviewing soon or currently, and think that you can wing the interview
because you’re good, DON’T. PRACTICE your data structures and algorithms. Take it
from someone who made the same mistake years ago.
The earlier you start practicing these coding interview questions, the better you get at
them, and the better the opportunities you get.
https://levelup.gitconnected.com/20-python-concepts-i-wish-i-knew-way-earlier-573cd189c183 11/24
5/26/23, 2:56 PM 20 Python Concepts I Wish I Knew Way Earlier | by Liu Zuo Lin | Apr, 2023 | Level Up Coding
^ lambda functions are simply normal functions, but written using a different syntax.
More examples:
def test():
return 'hello'
def test2(a,b,c,d):
return (a+b) / (c-d)
^ the assert keyword allows us to conduct a sanity test in the middle of our code. If
score > 100, an AssertionError is raised, and our program crashes forcefully.
^ the raise keyword allows us to forcefully cause an Exception (we can customize the
message in the Exeption too)
class ScoreException(Exception):
def __init__(self):
super().__init__('score cannot be higher than 100')
^ we can also create our own Exception types by inheriting from the Exception class.
https://levelup.gitconnected.com/20-python-concepts-i-wish-i-knew-way-earlier-573cd189c183 13/24
5/26/23, 2:56 PM 20 Python Concepts I Wish I Knew Way Earlier | by Liu Zuo Lin | Apr, 2023 | Level Up Coding
import multiprocessing
import time
import datetime
def yourfunction(x):
start = datetime.datetime.now()
time.sleep(1)
end = datetime.datetime.now()
return f'x={x} start at {start}, end at {end}'
if __name__ == '__main__':
with multiprocessing.Pool(processes=3) as pool:
data = pool.map(yourfunction, [1, 2, 3, 4, 5, 6, 7])
2. Consider signing up for a Medium membership using my link — it’s $5 per month and
you get to read unlimited stories on Medium.
https://levelup.gitconnected.com/20-python-concepts-i-wish-i-knew-way-earlier-573cd189c183 14/24
5/26/23, 2:56 PM 20 Python Concepts I Wish I Knew Way Earlier | by Liu Zuo Lin | Apr, 2023 | Level Up Coding
I write Python articles (sometimes other stuff) that the younger me would have wanted to
read. Do join my email list to get notified whenever I publish.
Level Up Coding
Thanks for being a part of our community! Before you go:
https://levelup.gitconnected.com/20-python-concepts-i-wish-i-knew-way-earlier-573cd189c183 15/24
5/26/23, 2:56 PM 20 Python Concepts I Wish I Knew Way Earlier | by Liu Zuo Lin | Apr, 2023 | Level Up Coding
Follow
https://levelup.gitconnected.com/20-python-concepts-i-wish-i-knew-way-earlier-573cd189c183 16/24
5/26/23, 2:56 PM 20 Python Concepts I Wish I Knew Way Earlier | by Liu Zuo Lin | Apr, 2023 | Level Up Coding
1.5K 5
Search Medium
https://levelup.gitconnected.com/20-python-concepts-i-wish-i-knew-way-earlier-573cd189c183 17/24
5/26/23, 2:56 PM 20 Python Concepts I Wish I Knew Way Earlier | by Liu Zuo Lin | Apr, 2023 | Level Up Coding
AutoGPT is Taking Over the Internet: Here Are the Incredible Use Cases
That Will Blow Your Mind
From acting as an intern to automating your work on Discord.
2.3K 31
4K 124
https://levelup.gitconnected.com/20-python-concepts-i-wish-i-knew-way-earlier-573cd189c183 18/24
5/26/23, 2:56 PM 20 Python Concepts I Wish I Knew Way Earlier | by Liu Zuo Lin | Apr, 2023 | Level Up Coding
540 2
https://levelup.gitconnected.com/20-python-concepts-i-wish-i-knew-way-earlier-573cd189c183 19/24
5/26/23, 2:56 PM 20 Python Concepts I Wish I Knew Way Earlier | by Liu Zuo Lin | Apr, 2023 | Level Up Coding
20K 369
https://levelup.gitconnected.com/20-python-concepts-i-wish-i-knew-way-earlier-573cd189c183 20/24
5/26/23, 2:56 PM 20 Python Concepts I Wish I Knew Way Earlier | by Liu Zuo Lin | Apr, 2023 | Level Up Coding
4K 124
Lists
https://levelup.gitconnected.com/20-python-concepts-i-wish-i-knew-way-earlier-573cd189c183 21/24
5/26/23, 2:56 PM 20 Python Concepts I Wish I Knew Way Earlier | by Liu Zuo Lin | Apr, 2023 | Level Up Coding
1.3K 21
https://levelup.gitconnected.com/20-python-concepts-i-wish-i-knew-way-earlier-573cd189c183 22/24
5/26/23, 2:56 PM 20 Python Concepts I Wish I Knew Way Earlier | by Liu Zuo Lin | Apr, 2023 | Level Up Coding
1K 9
https://levelup.gitconnected.com/20-python-concepts-i-wish-i-knew-way-earlier-573cd189c183 23/24
5/26/23, 2:56 PM 20 Python Concepts I Wish I Knew Way Earlier | by Liu Zuo Lin | Apr, 2023 | Level Up Coding
2K 16
787 9
https://levelup.gitconnected.com/20-python-concepts-i-wish-i-knew-way-earlier-573cd189c183 24/24