Fundamentals 8 min read

12 Essential Python Tricks Every Developer Should Know

This article presents twelve practical Python tricks—from retrieving string indices and adding progress bars to creating simple GUIs, converting strings to snake_case, flattening lists, sorting by index, generating UUIDs, initializing 2D lists, transposing iterables, using f‑strings, concatenating lists, and applying the walrus operator.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
12 Essential Python Tricks Every Developer Should Know

In this article we share twelve practical Python tips and code snippets that you can bookmark for future use.

1. Get String Index

This simple code shows how to obtain the starting index of any word or character in a string.

# Get String of String
string = "Here we go Python Coders"
print(string.index("Here"))  # 0
print(string.index("go"))    # 8
print(string.index("Coders"))  # 18

2. Progress Bar

If your program needs a progress bar, you can use the progress library.

# To install use "pip install progress"
from progress.bar import Bar
bar = Bar('Processing', max=100)
for i in range(100):
    # Do some work
    bar.next()
bar.finish()
# Output:
# Processing |###############               | 52/100

3. Simple GUI Code

Python offers several GUI modules. Below are three basic examples using tkinter, PyQt5, and wxPython.

tkinter

# Simple Gui Code
# tkinter
from tkinter import *
window = Tk()
window.title("Tkinter Code")
window.mainloop()

PyQt5

# PyQt
import sys
from PyQt5.QtWidgets import QApplication, QWidget
def main():
    app = QApplication(sys.argv)
    win = QWidget()
    win.resize(250, 250)
    win.setWindowTitle('Pyqt5')
    win.show()
    sys.exit(app.exec_())

wxPython

# Wxpython
import wx
app = wx.App()
frame = wx.Frame(None, title='WxPython')
frame.Show()
app.MainLoop()

4. String to Snake Case

This function converts a string to snake_case by inserting underscores between words and lower‑casing the result.

# String to Snake Case
from re import sub
def Snake(string):
    return '_'.join(sub('([A-Z][a-z]+)', r' \1',
        sub('([A-Z]+)', r' \1',
        string.replace('-', ' '))).split()).lower()
print(Snake("all the programmer"))  # all_the_programmer
print(Snake("something new"))      # something_new
print(Snake("snake case"))         # snake_case

5. Flatten a 2D List with sum()

You can flatten a two‑dimensional list using the built‑in sum() function.

list1 = [[1, 2], [9, 2], [5, 7, 8]]
flatten = sum(list1, [])
print(flatten)  # [1, 2, 9, 2, 5, 7, 8]

6. Sort by Index

This snippet sorts a list according to a separate list of indexes.

# Sort by Indexes
def Sort_By_Index(mylist, index):
    return [val for (_, val) in sorted(zip(index, mylist), key=lambda x: x[0])]
lst = ["apple", "mango", "bananna", "Pineapple"]
index = [3, 1, 4, 2]
print(Sort_By_Index(lst, index))  # ['mango', 'Pineapple', 'apple', 'bananna']

7. Generate Unique IDs

The built‑in uuid module can generate random unique identifiers (UUID1‑UUID5).

# Generate Unique ID
import uuid
print("Random ID is :", uuid.uuid1())
print("Random ID is :", uuid.uuid4())

8. Initialize a 2D List

Two ways to create a two‑dimensional list without external libraries.

# 2d List Initializing
# Way 1
mylist = [[2]*3 for _ in range(2)]
print(mylist)  # [[2, 2, 2], [2, 2, 2]]
# Way 2
mylist2 = [[0]*3 for i in range(3)]
print(mylist2)  # [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

9. Transpose an Iterable

Use zip(*iterable) to transpose a list of lists.

mylist = [[1, 2], [3, 4], [5, 6]]
result = list(zip(*mylist))
print(result)  # [(1, 3, 5), (2, 4, 6)]

10. Format Strings with F‑Strings

F‑strings provide a concise way to embed expressions inside string literals.

# String Formating with F-String
a = "Pythonior"
b = "Medium"
str1 = f"Do you want to become a {a}"
print(str1)
str2 = f"Medium had tons of {b} to make you {a}"
print(str2)
# Output:
# Do you want to become a Pythonior
# Medium had tons of Medium to make you Pythonior

11. Concatenate Two Lists

The + operator joins two lists.

# Sum up two List
list1 = [12, 13, 14, 15]
list2 = [16, 17]
newlist = list1 + list2
print(newlist)  # [12, 13, 14, 15, 16, 17]

12. Walrus Operator

The walrus operator ( :=) assigns a value to a variable as part of an expression.

# Walrus Operator
mylist = [1, 2, 3, 4]
if len(mylist) > 2:
    print(f"Length is {len(mylist)} which is greater")
if (n := len(mylist)) > 2:
    print(f"Length is {n} which is greater")

That concludes the article; I hope you find these snippets useful.

GUIFundamentalsData Manipulationcode-snippets
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.