Fundamentals 8 min read

Python Basics: Fundamental Operations and Code Snippets

This article presents a concise collection of 40 Python one‑liners covering fundamental operations such as printing, comprehensions, file handling, string manipulation, mathematical calculations, data structure manipulations, and useful built‑in functions, each illustrated with clear code examples.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Python Basics: Fundamental Operations and Code Snippets

Fundamental Operations

1. Print "Hello, World!": print("Hello, World!")

2. List comprehension to create a list of squares: squares = [x**2 for x in range(10)]

3. Dictionary comprehension to create a dictionary of squares: dict_comp = {x: x**2 for x in (2, 4, 6)}

4. Set comprehension to create a set of unique characters: set_comp = {x for x in 'abracadabra'}

5. Lambda expression for an anonymous addition function: add = lambda x, y: x + y

Data Processing

6. Filter even numbers from a range: even_numbers = list(filter(lambda x: x % 2 == 0, range(10)))

7. Map each number to its square: squared = list(map(lambda x: x**2, range(10)))

8. Sum of numbers 0‑9: sum_of_numbers = sum(range(10))

9. Maximum value in a list: max_number = max([1, 3, 5, 7, 9])

10. Minimum value in a list: min_number = min([2, 4, 6, 8, 10])

File Operations

11. Read all lines from a file: lines = [line.strip() for line in open('file.txt', 'r', encoding='utf-8')]

12. Write a line to a file: open('output.txt', 'w', encoding='utf-8').write('Hello, World!')

13. Check if a file exists: import os; file_exists = os.path.isfile('file.txt')

String Operations

14. Convert to uppercase: upper_str = "hello world".upper()

15. Convert to lowercase: lower_str = "HELLO WORLD".lower()

16. Palindrome check using slicing: is_palindrome = lambda s: s == s[::-1]

17. Replace a substring: replaced = "hello world".replace("world", "Python")

18. Split a string into a list: split_list = "apple,banana,cherry".split(',')

Mathematical Operations

19. Recursive factorial: factorial = lambda n: 1 if n == 0 else n * factorial(n-1)

20. Recursive Fibonacci: fibonacci = lambda n: n if n <= 1 else fibonacci(n-1) + fibonacci(n-2)

21. Greatest common divisor: from math import gcd; gcd_value = gcd(48, 18)

22. Least common multiple: from math import lcm; lcm_value = lcm(4, 6)

List Operations

23. Merge two lists: combined = [1, 2, 3] + [4, 5, 6]

24. Reverse a list using slicing: reversed_list = [1, 2, 3, 4, 5][::-1]

25. Find index of an element: index = [1, 2, 3, 4, 5].index(3)

26. Remove duplicates while preserving order: unique = list(dict.fromkeys([1, 2, 2, 3, 4, 4, 5]))

27. Check if a list is empty: my_list = []; is_empty = not my_list # returns True if empty, otherwise False

Dictionary Operations

28. Merge two dictionaries: merged = {**{'a': 1, 'b': 2}, **{'c': 3, 'd': 4}}

29. Get all keys: keys = list({'a': 1, 'b': 2}.keys())

30. Get all values: values = list({'a': 1, 'b': 2}.values())

31. Check key existence: key_exists = 'a' in {'a': 1, 'b': 2}

Set Operations

32. Union of two sets: union_set = set([1, 2, 3]).union(set([3, 4, 5]))

33. Intersection of two sets: intersection_set = set([1, 2, 3]) & set([2, 3, 4])

34. Difference of two sets: difference_set = set([1, 2, 3]) - set([2, 3, 4])

35. Symmetric difference of two sets: symmetric_difference_set = set([1, 2, 3]) ^ set([2, 3, 4])

Other Tips

36. Iterate two lists in parallel with zip : pairs = list(zip([1, 2, 3], ['a', 'b', 'c']))

37. Get index and value with enumerate : indexed = list(enumerate(['apple', 'banana', 'cherry']))

38. Check if any element satisfies a condition: any_true = any(x > 5 for x in [1, 2, 6, 4])

39. Check if all elements satisfy a condition: all_true = all(x < 10 for x in [1, 2, 3, 4, 9])

40. Sort a list: sorted_list = sorted([3, 1, 4, 1, 5, 9])

These one‑line snippets demonstrate Python's versatility and provide a quick reference for writing concise, efficient code.

PythonData StructuresAlgorithmsfundamentalscode snippets
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login 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.