Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Follow publication

Member-only story

20 Python Concepts I Wish I Knew Way Earlier

Liu Zuo Lin
Level Up Coding
Published in
9 min readApr 16, 2023

--

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.

1) Tuple Unpacking + Tuple Unpacking With *

person = ['bob', 30, 'male']

name, age, gender = person

# name='bob, age=30, gender='male'

^ we can use tuple unpacking to assign multiple variables at one go.

fruits = ['apple', 'orange', 'pear', 'pineapple', 'durian', 'banana']

first, second, *others = fruits

# first='apple', second='orange'
# others = ['pear', 'pineapple', 'durian', 'banana']

^ we can add * in front of variables to unpack everything else into that variable.

2) List Comprehension + Dict/Set Comprehension

lis = [expression for i in iterable if condition]
l1 = [i for i in range(1,4)]              # [1,2,3]

l2 = [i*2 for i in range(1,4)] # [2,4,6]

l3 = [i**2 for i in range(1,4)] # [1,4,9]

l4 = [i for i in range(1,4) if i%2==1] # [1,3]

^ with list comprehension, we can create a custom list in one line of code.

set1 = {i for i in range(1,4)}          # {1,2,3}

d1 = {i:i**2 for i in range(1,4)} # {1:1, 2:4, 3:9}

^ 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'

^ a normal if-elif-else block

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.

4) Magic Methods In Python Classes

class Dog():
def __init__(self, name, age)…

--

--