Python Tricks 101: Five Must‑Know Techniques for New Programmers
This article introduces five practical Python tricks—including string operations, list comprehensions, lambda with map, single‑line conditional expressions, and the zip function—providing clear explanations and code examples that help beginners write more concise and readable code.
When starting with Python, mastering a few key techniques can make your code more elegant and efficient. This article presents five useful tricks that are especially valuable for beginners.
String Operations – Strings support the + and * operators for concatenation and repetition, and slicing such as my_string[::-1] returns the reversed string. Example:
>> my_string = "Hi Medium..!"
>>> print(my_string * 2)
Hi Medium..!Hi Medium..!
>>> print(my_string + " I love Python" * 2)
Hi Medium..! I love Python I love PythonLists can be joined into a single string using ' '.join(word_list[::-1]) :
>> word_list = ["awesome", "is", "this"]
>>> print(' '.join(word_list[::-1]) + '!')
this is awesome!List Comprehensions – A concise way to create new lists. Instead of a loop with append , you can write:
>> my_list = [1, 2, 3, 4, 5]
>>> print([stupid_func(x) for x in my_list if x % 2 != 0])
[6, 14, 30]The general syntax is [expression for item in iterable if condition] , which is equivalent to a traditional for‑loop with an optional if block.
Lambda and Map – Lambda creates anonymous functions for quick operations. Example of applying a lambda with map to multiply two lists:
>> print(list(map(lambda x, y: x * y, [1, 2, 3], [4, 5, 6])))
[4, 10, 18]Lambda can also be used as a custom key for sorted :
>> my_list = [2, 1, 0, -1, -2]
>>> print(sorted(my_list, key=lambda x: x**2))
[0, -1, 1, -2, 2]Single‑Line Conditional Statements – Conditional logic can be embedded directly in expressions, reducing multiple lines to one:
>> print("Horse" if x >= 10 else "Duck" if 1 < x < 10 else "Baguette")zip() – Combines two equal‑length iterables into pairs, which can then be processed together. Example of merging first and last names:
>> first_names = ["Peter", "Christian", "Klaus"]
>>> last_names = ["Jensen", "Smith", "Nistrup"]
>>> print([ ' '.join(x) for x in zip(first_names, last_names)])
['Peter Jensen', 'Christian Smith', 'Klaus Nistrup']These five techniques—string operations, list comprehensions, lambda with map, single‑line conditionals, and zip—provide powerful tools for writing concise, readable Python code.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.