6 Python Tips & Tricks that no One Teaches 🚀🐍
Tags: python, tutorial, beginners, programming
Published: 2021-04-26 12:46:00

Python is currently the most used programming language in the world, and the unique reason is that Python developers are happy building software with it.

Its easy syntax, an extensive amount of libraries, and fast learning curve have gained the hearth of both beginners and experienced developers.

So today I'll share 6 of the best Python tricks that are not usually taught. 😃

All the examples are on this [Github repo](https://worldindev.ck.page), available after subscribing, so be sure to take a look at them.

--> Access and Download the source code of this article [here](https://worldindev.ck.page)

---

&nbsp;

## 🎉 Giveaway ⚡

We are giving away any course you need on Udemy. Any price any course.
To enter you have to do the following:
1. 👍 React to this post
1. ✉️ Subscribe to our [newsletter](https://worldindev.ck.page) <-- Very important

&nbsp;

---

## Select a random element from a sequence

The `random` package from the standard library has a lot of useful functions. But `random.choice(seq)` is a particularly useful one.

It allows you to pick a random element from an indexable sequence, for example, `lists`, `tuples`, or even `strings`

```python
import random as r
my_list = [1, 2, 3, "go"]
print(r.choice(my_list))

# Random item
```

### Practical example

A book picker function that receives a sequence of books gets a random choice, removes the item from the list, and returns the choice as a string

```python
# We import only the function we need
from random import choice

def book_picker(books):
    book_choice = choice(books)
    books.remove(book_choice)    
    return f"You picked {book_choice}"

books = ["Harry potter", "Don Quixote", "Learn Python by Daniel Diaz", "Dracula"]

print(book_picker(books)) # Random choice

print(books) # Remaining books
``` 

### Limitations and Exceptions

If you try to use `random.choice(seq)` in a non-indexable sequence, for example, `dictionaries`, `sets`, and `numeric types`, Python will raise an Error. 

```python
# With Dictionary
import random as r
scores = {"Jhon": 4, "Ben": 3, "Diana": 5}

print(r.choice(my_scores)) # Key error
```

Also if the sequence is empty Python will raise an `IndexError`.

```python
# With an empty sequence
import random as r
empty_list = []

print(r.choice(empty_list)) # Index error
```

## Unpacking elements with `*`

Sometimes we need to print the elements of an iterable separated by a space, and the most common solution I've seen is

```python
my_list = [1, 2, 3, 5, 7]

for i in my_list:
   print(i, end=" ") # 1 2 3 5 7 
```
Although this solves the problem, the code isn't that **pythonic**. There is a simpler solution using the unpacking operator "*"

```python
my_list = [1, 2, 3, 5, 7]

print(*mylist) # 1 2 3 5 7 
```

As you can see the unpack operator is always set at the left of an iterable, and it tells Python:

> Assign each element from this iterable to the desired tuple or list 

Remember that an iterable is any sequence we can iterate over with a for loop. If you want to check if a data type is iterable, use the `iter()` function.

```python

print(iter("This is a string")) # Str Iterable object

print(iter(["this", "is", "a", "list"])) # List iterable object

print(iter(1))
# Raises an error
# Integers can't be iterated
```

### Using unpacking with variables

Probably after you know the power of the unpacking operator, you would like to use it to store data in variables. So let's see how to do it

```python

string = "Let's learn Python"

# We want to assign the unpacked result in var1
var1 = [*string]

print(var1)
# ['L', 'e', 't', "'", 's', ' ', 'l', 'e', 'a', 'r', 'n', ' ', 'P', 'y', 't', 'h', 'o', 'n']
```

The `[*iterable]` part may look confusing so let me explain it. 

When we unpack an iterable python needs some data structure to store each element of that iterable, therefore we are creating a list (`[]`) outside the `*` operator.

If we try to get the type of a variable resulting from the `*` operator we get

```python
another_str = "The * operator"

# Using a list outside the unpacking
var2 = [*another_str]

print(type(var2)) # List

# Using a tuple
# Tuples ends with a comma
var3 = (*another_str,)

print(type(var3)) # Tuple
```

Of course, if you try to unpack without a list or tuple outside, you'll get a `SyntaxError`

```python
bad_variable = *"Bad String"
# Syntax error
```

Unpacking has much more uses, and I could do an exclusive article about it. 😀
 

## Using `set` to optimize operations

According to the [python documentation](https://docs.python.org/3/library/functions.html#func-set), the `set(iterable)` class creates a set object from an iterable.

As some of you may know a set is an unordered data structure, (therefore non-indexable) and one of its characteristics is that doesn't allow duplicated items.

### Practical example

Function that removes duplicates, and returns a sorted list.

```python
def eliminate_duplicates(lst):
    """
    Returns a sorted list, without duplicates
    """ 
    new_list = list(set(lst)) 
    
    new_list.sort()    
    
    return new_list

list1 = [25, 12, 11, 4, 12, 12, 25]

print(eliminate_duplicates(list1))
```

## View attrs and methods of a class without exiting the editor

The `dir()` function returns the attributes and methods of a class. We can use this useful trick to list all the definitions inside a class type.

```python
-> $ python 
string = "A string"

print(dir(string))

# ['__add__', .....,'upper', 'zfill']
```
For example, if we were looking for a string method that will convert our string into uppercase, and we are just too lazy to open the browser, we just run the `dir` function with a string as an argument and search for the right method

### Practical example

The best approach we can get from `dir` is when using 3rd party packages, we can get all the info we need from a class without exiting the terminal

```python
-> $ python


from django.views import View

print(dir(View))

# ['__class__', '__delattr__', .... 'setup']
```

## Slices Operations 

A slice is nothing but a way of accessing certain parts of a sequence. In python, slices allow us to do multiple tricks.  

### Reversing sequences

```python
# Reversing lists
lst = ["Fun", "is", "Programming"]

lst = lst[::-1]

print(lst) # ['Programming', 'is', 'Fun']

# Reversing strings

string = "Dog running on the park"

string = string[::-1]

print(string) # krap eht no gninnur goD
```

## Practical example

Function that returns a sequence until the given index

```python
def cutoff(seq, index):
    if not len(seq) > index:
        return "Sorry the index is bigger than the sequence"

    return seq[:index]

long_string = "This is a long description of a blog post about Python and technology"

print(cutoff(long_string, 15))
# This is a long 

print(cutoff(long_string, 70))
# Sorry the index is bigger than the sequence
```

## Call a debugger in 10 letters

The function `breakpoint` is available from python 3.6+. This will call a session of `pdb.set_trace()`.

It may sound like a pure convenience (And maybe it does) but for me is a really short and elegant way of calling a debugger

### Example

```python
n_odds = 0

for i in range(1, 14, 2):
    # Check for the value of i in each iteration
    breakpoint()
    # Bad condition
    if i % 2 == 0:
        n_odds += 1

print(n_odds)
```

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4dx7ddspcdj2d16g6mpu.png)

## Conclusion

In this tutorial, you learned:
- To choose a random element from a sequence
- To unpack elements with  `*` operator
- The ability of sets to deleting duplicates efficiently
- How to search for methods and variables without exiting the code editor
- The diverse uses of python slices
- How to call a debugger with the function `breakpoint`

> Please consider supporting me on [Ko-fi](https://ko-fi.com/daniel1404). You would help me to continue building these tutorials!.
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/Y8Y03P8P1)

If you have any feedback please, let me know in the comments!

---

Read also:

{% link https://dev.to/worldindev/5-css-tricks-tips-that-you-should-know-giveaway-4d0d %}

{% link https://dev.to/worldindev/8-javascript-tips-tricks-that-no-one-teaches-24g1 %}