DEV Community

Rounak Sen
Rounak Sen

Posted on

Unleashing Pythonic Wizardry🧙🏿‍♂️: Tips to Embrace the Art of Elegant Pythonic Writing 🐍

Python, with its boundless capabilities and unmatched adaptability, transcends the realm of ordinary programming languages. While it shines brightly in its versatility, Python is no mere contender in the vast arena of coding tools.

But Python’s allure runs deeper than its pragmatic utility. It embodies a philosophy, a way of thinking that permeates every line of code. Pythonic writing, as if breathing life into the very essence of programming, encapsulates a mindset of clarity, simplicity, and beauty. It goes beyond the mechanics of coding, transcending into an art form where readability and elegance reign supreme.

So without any further delay lets begin with some tips to embrace the art of elegant Pythonic writing.

Image description

Tip 1: Inplace swap 🅰️↔️🅱️

Instead of taking a temporary variable to store a value and then swap like other programming languages, Python can swap variables in ONE line all thanks to the tuple destructuring or tuple unpacking .

a = 2
b = 5
a, b = b, a # this equals (a, b) = (b, a)
print(a) # 5
print(b) # 2
Enter fullscreen mode Exit fullscreen mode

Tip 2: Tuple / List Unpacking 🔓📦

This is equal to assigning multiple variables from a list or tuple in a single line.

a, b, c = [11, 12, 13] # works also for (11, 12, 13)
print(a) # 11
print(b) # 12
print(c) # 13      
Enter fullscreen mode Exit fullscreen mode

you can use this feature to pass arguments and keyword arguments to a function using ‘’ for list or tuples and ‘*’ for dictionaries.

args = [1, 2, "a"]
kwargs = {"a": 5, "b": 21}
some_func(*args, **kwargs) # * for list or tuple and ** for dicts
Enter fullscreen mode Exit fullscreen mode

Unpacking

Tip 2: Tuple / List Packing 🔒📦

Just like unpacking you can also pack some values in a variable using ‘*’.

first, rest*, last = [1, 2, 3, 4, 5] # works also for (1, 2, 3, 4, 5)
print(first) # 1
print(rest) # [2, 3, 4]
print(last) # 5
Enter fullscreen mode Exit fullscreen mode

You can also get packed arguments using ‘*’.

def some_function(*args, **kwargs):
    print(f"Args: {args}")
    print(f"Kwargs: {kwargs}")

some_function(1, 2, 3,  a=4, b=5, c=6)
# Args: (1, 2, 3)
# Kwargs: {'a': 4, 'b': 5, 'c': 6}  
Enter fullscreen mode Exit fullscreen mode

BONUS TIP: NEVER Trust your user to ALWAYS pass correct Input.

Packing

Tip 4: Store you Garbage in ‘_’ ️🗑️

Python offers you ‘_’ as a valid variable name so why not store your garbage in it.

for _ in range(100):
  print("Useless _")
Enter fullscreen mode Exit fullscreen mode

Tip 5: Loop correctly ♾️

Instead of index looping on Index like other languages use the value of the element in list or tiple or dict to loop.

for x in [1, 2, 3]: # No use of index
  print(x)

dict_ = {"a": 1, "b":2, "c": 3}

# dict.items() returns list of (key, value) tuples.
for key, value in dict_.items(): 
  print(key, value)
Enter fullscreen mode Exit fullscreen mode

And If you need Index you have enumerate() to help you

list_ = [1, 2, 3]
# enumerate return list of (key, value) tuples.
for idx, value in enumerate(list_):
  print(idx, value)
Enter fullscreen mode Exit fullscreen mode

loop infinite

Tip 6: Better Numbers ️🔢

Just use pythons underscored numbers to give a much better readable numbers.

num = 100_000_000 # much better than 100000000
Enter fullscreen mode Exit fullscreen mode

Tip 7: f-strings f-strings f-strings all the way🔤

By far The BEST way to write dynamic stings is No doubt python’s f-strings. It works like magic and is very readable.

color = "Black"
animal = "Dog"
print(f"I saw a {color} {animal}.") # I saw a Black Dog.
Enter fullscreen mode Exit fullscreen mode

for multiline strings use

name, profession = "Geek", "Coder"
print(f"""
      Hi {name}. 
      You are a {profession}.
      """)
Enter fullscreen mode Exit fullscreen mode

AND did I forgot to mention they are DAMM FAST.

Tip 8: Slicing is FUN 🍰🍕

In python slicing is as easy as accessing the value from a list or tuple. In other programming languages slicing is done using calling a method or function. but python has streamlined slicing by making it access able in third backet notation in format [start : stop_before : separation] also including negative index(from last element).

list_ = [1, 2, 3, 4, 5]
print(list_[:2]) # [1, 2, 3]
print(list_[0:5:2]) # [1, 3, 5]
Enter fullscreen mode Exit fullscreen mode

You can also reverse a list by using [::-1]

list_ = [1, 2, 3, 4, 5]
print(list_[::-1]) # [5, 4, 3, 2, 1]
Enter fullscreen mode Exit fullscreen mode

Phil swift chainsaw

Tip 9: Better IF ELSE 🕹️

If you have simple if else statement you can use python if else expression to achieve your task. This is a replacement of ternary operator from other languages. Its syntax is in form

TRUE if CONDITION else FALSE

print("YES" if 10 > 5 else "NO")
Enter fullscreen mode Exit fullscreen mode

If you are familiar with other language’s ternary operator this will take some time to get used to.

Tip 10: Cool LAMBDAs ️⋋

Lambdas are great tool for doing some quick anonymous functions. this gives us a way to avoid one of the Programmer’s most dreadful decisions i.e. NAMING THINGS . they are generally used for one use mainly as a function to another functions.

square_lambda = lambda x: x**2
print(f"Lambda function: {square_lambda(4)}") # Lambda function: 16

# main use
map(lambda x: x+5, list_)
Enter fullscreen mode Exit fullscreen mode

phew

This Is just the beginning Intro to Python Magic There are More Magics to reveal. Python with a symphony of possibilities, an invitation to dream big and transform the world, one line of Pythonic brilliance at a time.

This is My first Blog I you Like It please share to spread Knowledge. And If you have any pointers or feedback feel free to comment it.

Top comments (0)