15 Minimalist Python Code Snippets for Beginners
The article offers fifteen ultra‑compact Python code snippets, each illustrating a common task—from printing hello world to reading files—providing beginners with quick, ready‑to‑use examples and brief explanations, plus a promotion for a free Python learning resource.
This article presents fifteen concise Python code examples that demonstrate common programming tasks, aimed at beginners seeking quick, practical solutions.
1. Print "Hello, World!" – The classic first program can be executed with a single line:
print("Hello, World!")2. Swap two variables – Python's tuple unpacking swaps values without a temporary variable:
a, b = 5, 10 a, b = b, a print(a, b)3. Sum elements of a list – Use the built‑in sum function:
nums = [1, 2, 3, 4, 5] print(sum(nums))4. Find maximum and minimum in a list – max and min return the largest and smallest values:
nums = [10, 5, 20, 3] print(max(nums), min(nums))5. Check if a string is empty – The boolean value of a string combined with not does the check:
s = "" print(not s)6. Generate a list of numbers in a range – Combine range with list :
print(list(range(1, 11)))7. Count occurrences of a character in a string – Use the count method:
s = "hello world" print(s.count('l'))8. Remove duplicates from a list – Convert the list to a set :
nums = [1, 2, 2, 3, 3, 3] print(set(nums))9. One‑line conditional expression – The ternary operator returns a value based on a condition:
x = 10 result = "even" if x % 2 == 0 else "odd" print(result)10. Iterate over a list and print each element – A simple for loop:
fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)11. Split a string into a list of words – Use the split method:
s = "hello world python" print(s.split())12. Concatenate two lists – The + operator merges them:
list1 = [1, 2, 3] list2 = [4, 5, 6] print(list1 + list2)13. Compute the factorial of a number – A recursive function in a single line:
def factorial(n): return 1 if n == 0 else n * factorial(n - 1) print(factorial(5))14. Reverse a list – Slice notation with a step of -1 :
nums = [1, 2, 3, 4, 5] print(nums[::-1])15. Read all lines from a file – Use with and readlines :
with open('test.txt', 'r') as f: print(f.readlines())At the end of the article, readers are invited to scan a QR code to receive a free Python course and a collection of learning materials, including e‑books, tutorials, project templates, and source 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.