20 Python Concepts I Wish I Knew Way Earlier
<p>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.</p>
<h1>1) Tuple Unpacking + Tuple Unpacking With *</h1>
<pre>
person = ['bob', 30, 'male']
name, age, gender = person
# name='bob, age=30, gender='male'</pre>
<p>^ we can use tuple unpacking to assign multiple variables at one go.</p>
<pre>
fruits = ['apple', 'orange', 'pear', 'pineapple', 'durian', 'banana']
first, second, *others = fruits
# first='apple', second='orange'
# others = ['pear', 'pineapple', 'durian', 'banana']</pre>
<p>^ we can add <code>*</code> in front of variables to unpack <em>everything else</em> into that variable.</p>
<h1>2) List Comprehension + Dict/Set Comprehension</h1>
<pre>
lis = [expression for i in iterable if condition]</pre>
<pre>
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]</pre>
<p>^ with list comprehension, we can create a custom list in one line of code.</p>
<pre>
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}</pre>
<p>^ set comprehension and dictionary comprehension can be used to create sets and dictionaries in the same way we create lists using list comprehensions.</p>
<h1>3) Ternary operator</h1>
<pre>
score = 57
if score > 90:
grade = 'A*'
elif score > 50:
grade = 'pass'
else:
grade = 'fail'
# grade = 'pass'</pre>
<p>^ a normal if-elif-else block</p>
<pre>
score = 57
grade = 'A*' if score>90 else 'pass' if score>50 else 'fail'
# grade = 'pass'</pre>
<p>^ we can condense the if-elif-else block into ONE line using the ternary operator.</p>
<h1>4) Magic Methods In Python Classes</h1>
<pre>
class Dog():
def __init__(self, name, age)…</pre>
<p><a href="https://levelup.gitconnected.com/20-python-concepts-i-wish-i-knew-way-earlier-573cd189c183">Click Here</a></p>