Unleashing Pythonic Wizardry🧙🏿‍♂️: Tips to Embrace the Art of Elegant Pythonic Writing 🐍
Tags: python, programming, productivity
Published: 2023-05-09 11:11:02

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ebhlt7h4cqywlv5jsvqw.gif)
<br>
## **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 .
```python
a = 2
b = 5
a, b = b, a # this equals (a, b) = (b, a)
print(a) # 5
print(b) # 2
```
<br>
## **Tip 2: Tuple / List Unpacking 🔓📦**
This is equal to assigning multiple variables from a list or tuple in a single line.

```python
a, b, c = [11, 12, 13] # works also for (11, 12, 13)
print(a) # 11
print(b) # 12
print(c) # 13      
```
you can use this feature to pass arguments and keyword arguments to a function using ‘*’ for list or tuples and ‘**’ for dictionaries.

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

![Unpacking](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2pexml2b4pe1sd38jcsu.gif)


<br>
## **Tip 2: Tuple / List Packing 🔒📦**
Just like unpacking you can also pack some values in a variable using ‘*’.

```python
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
```

You can also get packed arguments using ‘*’.

```python
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}  
```

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


![Packing](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/phox2f8dnvwu9pv5zunp.gif)
<br>
## **Tip 4: Store you Garbage in ‘_’ ️🗑️**
Python offers you ‘_’ as a valid variable name so why not store your garbage in it.

```python
for _ in range(100):
  print("Useless _")
```
<br>
## **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.

```python
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)
```

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

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


![loop infinite](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6e9mii2e3m5vw8bbuqaj.gif)

<br>
## **Tip 6: Better Numbers ️🔢**
Just use pythons underscored numbers to give a much better readable numbers.

```python
num = 100_000_000 # much better than 100000000
```
<br>
## **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.

```python
color = "Black"
animal = "Dog"
print(f"I saw a {color} {animal}.") # I saw a Black Dog.
```

for multiline strings use

```python
name, profession = "Geek", "Coder"
print(f"""
      Hi {name}. 
      You are a {profession}.
      """)
```

AND did I forgot to mention they are DAMM FAST.
<br>
## **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).

```python
list_ = [1, 2, 3, 4, 5]
print(list_[:2]) # [1, 2, 3]
print(list_[0:5:2]) # [1, 3, 5]
```

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

```python
list_ = [1, 2, 3, 4, 5]
print(list_[::-1]) # [5, 4, 3, 2, 1]
```

![Phil swift chainsaw](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/osp7irwfo1fzvyj1l2yw.png)
<br/>
## **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**

```python
print("YES" if 10 > 5 else "NO")
```

If you are familiar with other language’s ternary operator this will take some time to get used to.
<br>
## **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.

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

# main use
map(lambda x: x+5, list_)
```

![phew](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/krmhpoezc6qn9ztkya9r.gif)
<br/>

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.