DEV Community

Nill Webdev
Nill Webdev

Posted on

3 Python Tips & Tricks that no One Teaches

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 3 of the best Python tricks that are not usually taught. 😃

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]

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

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

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.

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.

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

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 "*"

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.

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

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

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

bad_variable = *"Bad String"
Syntax error

Using set to optimize operations

According to the python documentation, 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.
def eliminate_duplicates(lst):
"""
Returns a sorted list, without duplicates
"""
new_list = list(set(lst))

new_list.sort()    

return new_list
Enter fullscreen mode Exit fullscreen mode

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

from django.views import View

print(dir(View))

['class', 'delattr', .... 'setup']

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

Top comments (0)