avatarYang Zhou

Summary

The web content provides 11 advanced Python programming techniques to enhance code elegance and efficiency, showcasing Pythonic practices for experienced developers.

Abstract

The article "11 Python Tricks To Show Off Your Advanced Skills" delves into sophisticated Python techniques that can elevate a developer's code to a more Pythonic and efficient level. It covers a range of topics from destructuring assignments and using the zip function to aggregate items, to leveraging lambda functions, list comprehensions, and handling text with regular expressions. The article also touches on the use of underscores to ignore variables, placing function placeholders, and the simplicity of shallow copying lists. Additionally, it demonstrates how to remove unnecessary spaces in strings and how to use the map and reduce functions effectively. The author emphasizes the importance of these techniques in writing concise and maintainable Python code, and encourages readers to explore further resources for a deeper understanding of Python's capabilities.

Opinions

  • The author suggests that mastering Python's syntax sugar, such as destructuring assignments and list comprehensions, is key to writing elegant Pythonic code.
  • Lambda functions are praised for their ability to provide concise one-liner solutions, particularly in filtering operations.
  • The use of underscores to ignore unwanted variables is presented as a convenient and readable practice.
  • Regular expressions are highlighted as a powerful tool for text handling, with Python's re module offering comprehensive functionality.
  • The map and reduce functions are considered powerful higher-order functions that can greatly enhance the functional programming capabilities of Python code.
  • The article promotes the combination of splits() and join() as an effective method for cleaning up strings by removing excess whitespace.
  • The simplicity of using list slicing for shallow copying is emphasized as a Pythonic technique that every developer should know.
  • The author finds it interesting and useful that the Python interpreter allows the use of an underscore to access the value of the last expression, aiding in quick debugging or reference.
  • The author encourages continuous learning and exploration of Python, suggesting that life is too short not to make the most of this versatile language.

11 Python Tricks To Show Off Your Advanced Skills

Let’s enjoy the elegance of Python

Image from Wallhaven

Python is an elegant language if you can use it in a Pythonic way.

But no matter how senior you are, it needs some time to really write code Pythonicly.

This article is to show you 11 Pythonic tricks to let your Python skills enter into a new realm.

Talk is cheap, let’s see the code now.

1. Destructuring Assignment in Python

Assigning values to variables is a basic operation of programming. Python has some syntax sugar to make the process more elegant.

Let’s see a simple example:

a, *mid, b = [1, 2, 3, 4, 5, 6]
print(a, mid, b)
# 1 [2, 3, 4, 5] 6

As shown above, with the help of one asterisk, the mid variable receives the items in the middle as a list.

2. Use Zip Function To Aggregates Items

Python has an amazing built-in function called zip. As its name implies, the zip function aggregates items from different iterables, such as lists, tuples or sets, and returns an iterator.

3. Use Lambda Functions in Python Properly

If you like one-liners. Lambda functions are your friends. Let’s see a classic question here:

Give you a list as following, can you print all the odd numbers within it?

numbers = [1, 12, 37, 43, 51, 62, 83, 43, 90, 2020]

Simple. You only need one line of code:

4. Ignore Variables Using Underscores

Sometimes, a variable is useless and you don’t bother to give it a name, you can use an underscore to ignore it.

>>> L = [1,3,5,7]
>>> a, _, b, _ = L
>>> print(a, b)
1 5

5. Leverage the Power of List Comprehension

Again, if you’re a fan of Python one-liners. The list comprehension is something you must know. It has the power to convert multiple operations into one line of code:

6. Put a Placeholder

Sometimes, you need to define a function but haven’t figure out how to implement it yet, you can put a placeholder inside it:

def my_func():
    pass

Or a cuter way: 🙂

def my_func():
    ...

7. Handle Text Through Regular Expressions

The regular expression (regex) is a powerful tool to deal with characters/strings. Python’s built-in re module provides all functionalities of regex:

import re
txt = "Yang is so handsome!!!"
x = re.search("Elon", txt)
print(x)
#None

8. Map and Reduce in Python

There are two famous higher-order functions in Python: map() and reduce().

The map() function receives two parameters, one is a function and the other is Iterable. It applies the initialized function to each element of the sequence in turn, and returns the result as a new Iterator.

The reduce() method also has two parameters, one is a function and the other is Iterable. It applies a function to a sequence, this function must receive two parameters, reduce continues the result and performs the cumulative calculation with the next element of the sequence. Finally, it returns the result of the cumulative calculation.

9. Remove Unnecessary Spaces in a String Elegantly

This string handling trick combines the power of splits() and join():

10. The Easiest Way To Shallow Copy a List

The simplest way to shallow copy a list in Python is leveraging the feature of list slicing:

>>> a = [1, 2, 3, 4, 5, 6]
>>> b = a[:]
>>> b[0]=100
>>> b
[100, 2, 3, 4, 5, 6]
>>> a
[1, 2, 3, 4, 5, 6]

11. Check the Last Expression’s Value in Interpreter

This is an interesting and small trick of Python Interpreter. We can use one underscore to simply get the last expression’s value.

>>> 5+6
11
>>> _
11

Go Further

Life is short, why not use Python?

If you would like to explore more details, don’t hesitate to check the list below:

Python
Programming
Coding
Technology
Engineering
Recommended from ReadMedium