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…


This content originally appeared on DEV Community and was authored by Daniel Diaz

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

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

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

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

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

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

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)

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!


This content originally appeared on DEV Community and was authored by Daniel Diaz


Print Share Comment Cite Upload Translate Updates
APA

Daniel Diaz | Sciencx (2021-04-26T12:46:00+00:00) 6 Python Tips & Tricks that no One Teaches ??. Retrieved from https://www.scien.cx/2021/04/26/6-python-tips-tricks-that-no-one-teaches-%f0%9f%9a%80%f0%9f%90%8d/

MLA
" » 6 Python Tips & Tricks that no One Teaches ??." Daniel Diaz | Sciencx - Monday April 26, 2021, https://www.scien.cx/2021/04/26/6-python-tips-tricks-that-no-one-teaches-%f0%9f%9a%80%f0%9f%90%8d/
HARVARD
Daniel Diaz | Sciencx Monday April 26, 2021 » 6 Python Tips & Tricks that no One Teaches ??., viewed ,<https://www.scien.cx/2021/04/26/6-python-tips-tricks-that-no-one-teaches-%f0%9f%9a%80%f0%9f%90%8d/>
VANCOUVER
Daniel Diaz | Sciencx - » 6 Python Tips & Tricks that no One Teaches ??. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/04/26/6-python-tips-tricks-that-no-one-teaches-%f0%9f%9a%80%f0%9f%90%8d/
CHICAGO
" » 6 Python Tips & Tricks that no One Teaches ??." Daniel Diaz | Sciencx - Accessed . https://www.scien.cx/2021/04/26/6-python-tips-tricks-that-no-one-teaches-%f0%9f%9a%80%f0%9f%90%8d/
IEEE
" » 6 Python Tips & Tricks that no One Teaches ??." Daniel Diaz | Sciencx [Online]. Available: https://www.scien.cx/2021/04/26/6-python-tips-tricks-that-no-one-teaches-%f0%9f%9a%80%f0%9f%90%8d/. [Accessed: ]
rf:citation
» 6 Python Tips & Tricks that no One Teaches ?? | Daniel Diaz | Sciencx | https://www.scien.cx/2021/04/26/6-python-tips-tricks-that-no-one-teaches-%f0%9f%9a%80%f0%9f%90%8d/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.