DEV Community

Cover image for 6 Python Tips & Tricks that no One Teaches πŸš€πŸ
Daniel Diaz for World In Dev

Posted on

6 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 6 of the best Python tricks that are not usually taught. πŸ˜ƒ

All the examples are on this Github repo, available after subscribing, so be sure to take a look at them.

--> Access and Download the source code of this article here


Β 

πŸŽ‰ 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
  2. βœ‰οΈ Subscribe to our newsletter <-- Very important

Β 


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

# Random item
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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']
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

bad_variable = *"Bad String"
# Syntax error
Enter fullscreen mode Exit fullscreen mode

Unpacking has much more uses, and I could do an exclusive article about it. πŸ˜€

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

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

print(eliminate_duplicates(list1))
Enter fullscreen mode Exit fullscreen mode

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']
Enter fullscreen mode Exit fullscreen mode

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']
Enter fullscreen mode Exit fullscreen mode

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

# 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
Enter fullscreen mode Exit fullscreen mode

Practical example

Function that returns a sequence until the given index

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
Enter fullscreen mode Exit fullscreen mode

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

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)
Enter fullscreen mode Exit fullscreen mode

image

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. You would help me to continue building these tutorials!.
ko-fi

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


Read also:

Latest comments (18)

Collapse
 
crestiancik profile image
Crestiancik • Edited

Wow, that is a really great post though! I am very surprised by those tricks and tips actually, as I did not even expect that you can do this kind of things. And, that is true, no one actually teaches you those things, which makes them even more amazing! I am learning python right now actually, and I have to tell you that most of the teachers tend to avoid from teaching us different useful tips and tricks, the only place where you could actually find these tricks are the python learning websites, nurtem.com/classes-and-camps/progr... is one of them, and probably the best one, at least the best ones.

Collapse
 
guptaarth87 profile image
guptaarth87

Amazing article keep it up

Collapse
 
arunj0shi profile image
Arun Joshi

fantastic article! i learnt many things new

Collapse
 
danidiaztech profile image
Daniel Diaz

Thanks for the feedback πŸ™

Collapse
 
deepcjoshi10 profile image
Deep

Great knowledge shared.. Keep up the good work

Collapse
 
codemouse92 profile image
Jason C. McDonald • Edited

Unpacking gets even better than that...

some_iterable = ["I", "have", "no", "idea", "how", "many", "values", "are", "here", "so", "this", "will", "be", "fun!"]
first, second, *_, last = *some_iterable
print(first, second, last)  # I have fun!
Enter fullscreen mode Exit fullscreen mode

You can include one starred name among the names to unpack into. Python will fill in all the others based on position, and then stuff the rest into the starred name.

In this case, I use _ for the name, because I really only intend to throw those away. _ is a completely valid name in Python, but it's conventionally used as a "throw away" name. If you're curious, you can still see what was parked in there in the above code with...

print(_)  # ['no', 'idea', 'how', 'many', 'values', 'are', 'here', 'so', 'this', 'will', 'be']
Enter fullscreen mode Exit fullscreen mode

P.S. Bit of shameless self-promotion, all of the above is in my forthcoming book "Dead Simple Python" (No Starch Press, 2021). So, it isn't quite that "no one" covers this stuff.

Collapse
 
devlorenzo profile image
DevLorenzo

If you want, you can add directly here the link πŸ˜‰

Collapse
 
codemouse92 profile image
Jason C. McDonald

Heh, I will once I have one. It'll be this fall, tho.

Collapse
 
danidiaztech profile image
Daniel Diaz

What such an amazing explanation Jason.🀯
That's exactly why I said the unpack operator deserves an isolated article.

BTW, I'd be glad to read your book.

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
danidiaztech profile image
Daniel Diaz

I'm glad you find it useful!

Collapse
 
coreyjs profile image
Corey Schaf

Nice! Some neat tips in here.

Collapse
 
danidiaztech profile image
Daniel Diaz

Thanks πŸ™πŸΌ

Collapse
 
cjsmocjsmo profile image
Charlie J Smotherman

You can use

some_list.reverse()

also

Collapse
 
danidiaztech profile image
Daniel Diaz

Of course. That is a useful method,

Collapse
 
ironcladdev profile image
Conner Ow

Sweet, man! I didn't even know these existed!!
The * python iterator is kind of like the ES6 [...arr] in a way.

Collapse
 
danidiaztech profile image
Daniel Diaz

It seems Python and Js are not that different 🀣

Collapse
 
devlorenzo profile image
DevLorenzo

Hey! I think I know you ...