In this article, we break down several powerful Python one-liners that perform complex tasks. Each section includes the code, an explanation of how it works, and a step-by-step breakdown.
1. Flatten a Nested List
1
2
3
4
5
| flattened = lambda lst: [x for sublist in lst for x in sublist]
# Example
nested_list = [[1, 2, 3], [4, 5], [6]]
print(flattened(nested_list)) # Output: [1, 2, 3, 4, 5, 6]
|
Breakdown
How It Works:
- The lambda function
flattened takes one parameter lst, which is expected to be a list containing other lists. - The list comprehension
[x for sublist in lst for x in sublist] uses two loops:- Outer loop: Iterates over each sublist in
lst. - Inner loop: Iterates over each element
x in the current sublist.
- All elements
x are collected into a new, flat list.
Step-by-Step:
- Iteration over Sublists:
For each sublist in the main list lst, the comprehension initiates an inner loop. - Iteration over Elements:
For each element x in the current sublist, x is added to the resulting list. - Result:
A single, flat list that contains all the elements from the nested sublists.
2. Find Prime Numbers in a Range
1
2
3
4
| primes = lambda n: [x for x in range(2, n) if all(x % i != 0 for i in range(2, int(x**0.5) + 1))]
# Example
print(primes(20)) # Output: [2, 3, 5, 7, 11, 13, 17, 19]
|
Breakdown
How It Works:
- The lambda function
primes takes one parameter n, representing the upper limit (exclusive) for prime checking. - The list comprehension iterates over each number
x from 2 to n-1. - The generator expression
all(x % i != 0 for i in range(2, int(x**0.5) + 1)) checks that x is not divisible by any number from 2 up to int(x**0.5) + 1. - The number
x is included in the list only if it passes the divisibility test (i.e., it is prime).
Step-by-Step:
- Candidate Generation:
Generate candidates from 2 up to n-1. - Divisibility Check:
For each candidate x, test divisibility by every number i from 2 to int(x**0.5) + 1. - Validation:
Use all() to ensure x has no divisors in the specified range. - Result:
A list of all prime numbers less than n is produced.
3. Find the Most Frequent Element in a List
1
2
3
4
5
6
| from collections import Counter
most_frequent = lambda lst: Counter(lst).most_common(1)[0][0]
# Example
nums = [1, 3, 2, 3, 4, 3, 5]
print(most_frequent(nums)) # Output: 3
|
Breakdown
How It Works:
- The
Counter from the collections module counts the occurrences of each element in the list lst. - The method
most_common(1) returns a list with the single most common element as a tuple: (element, count). - Indexing
[0][0] extracts the element from the tuple.
Step-by-Step:
- Counting Elements:
Counter(lst) tallies the frequency of each element in the list. - Extracting the Most Common:
most_common(1) identifies the element with the highest occurrence. - Final Extraction:
Access the first tuple and then the element within it. - Result:
The most frequent element in the list is returned.
4. Read and Process a File in One Line
1
2
3
4
5
| lines = [line.strip() for line in open("file.txt")]
# Example (assuming file.txt exists and contains text)
for line in lines:
print(line)
|
Breakdown
How It Works:
open("file.txt") opens the file in read mode.- The list comprehension iterates over each line in the file.
line.strip() removes leading and trailing whitespace from each line.- The result is a list of cleaned lines.
Step-by-Step:
- File Opening:
The file "file.txt" is opened for reading. - Iteration:
Iterate over each line in the file. - Whitespace Removal:
Use strip() to remove extra spaces or newline characters. - Result:
A list of processed lines is created.
Note: In practice, use a context manager (with open(...) as f:) to ensure proper file closure.
5. Swap Keys and Values in a Dictionary
1
2
3
4
5
| swapped_dict = lambda d: {v: k for k, v in d.items()}
# Example
d = {'a': 1, 'b': 2, 'c': 3}
print(swapped_dict(d)) # Output: {1: 'a', 2: 'b', 3: 'c'}
|
Breakdown
How It Works:
- The lambda function
swapped_dict takes a dictionary d as input. d.items() returns key-value pairs from the dictionary.- A dictionary comprehension creates a new dictionary where each value
v becomes a key, and each key k becomes a value.
Step-by-Step:
- Extracting Items:
Iterate over each (key, value) pair using d.items(). - Swapping:
For each pair, create a new pair with the value as the new key and the key as the new value. - Result:
A new dictionary with swapped keys and values is returned.
6. Check If a String is a Palindrome
1
2
3
4
5
| is_palindrome = lambda s: s == s[::-1]
# Example
print(is_palindrome("racecar")) # Output: True
print(is_palindrome("hello")) # Output: False
|
Breakdown
How It Works:
- The lambda function
is_palindrome compares a string s with its reverse s[::-1]. - The slice notation
s[::-1] creates a reversed copy of the string. - If the original string and its reverse are identical, the string is a palindrome.
Step-by-Step:
- Reversing the String:
Use slicing s[::-1] to obtain the reversed string. - Comparison:
Compare the reversed string with the original string s. - Result:
Returns True if they match (palindrome), otherwise False.
7. Merge Two Lists into a Dictionary
1
2
3
4
5
6
| merge_dict = lambda keys, values: dict(zip(keys, values))
# Example
keys = ['name', 'age']
values = ['Alice', 25]
print(merge_dict(keys, values)) # Output: {'name': 'Alice', 'age': 25}
|
Breakdown
How It Works:
- The lambda function
merge_dict takes two lists: one of keys and one of values. zip(keys, values) pairs each key with its corresponding value.- The
dict() constructor converts these pairs into a dictionary.
Step-by-Step:
- Pairing Elements:
Use zip(keys, values) to create pairs from the two lists. - Dictionary Construction:
Convert the zipped pairs into a dictionary using dict(). - Result:
A dictionary mapping keys to their corresponding values is returned.
8. Generate Fibonacci Sequence
1
2
3
4
5
| from functools import reduce
fibonacci = lambda n: reduce(lambda x, _: x + [x[-1] + x[-2]], range(n - 2), [0, 1])
# Example
print(fibonacci(10)) # Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
|
Breakdown
How It Works:
- The lambda function
fibonacci generates the first n Fibonacci numbers. - It uses
reduce() to accumulate the Fibonacci sequence. - The accumulator starts with
[0, 1], the first two Fibonacci numbers. - For each iteration, a new Fibonacci number is calculated as the sum of the last two numbers and appended to the list.
Step-by-Step:
- Initialization:
Start with the list [0, 1]. - Iteration:
Use range(n - 2) to iterate for the remaining Fibonacci numbers. - Calculation:
For each iteration, calculate the next number as x[-1] + x[-2]. - Appending:
Append the new number to the list. - Result:
The complete list of the first n Fibonacci numbers is returned.
9. Reverse Words in a Sentence
1
2
3
4
| reverse_words = lambda s: " ".join(s.split()[::-1])
# Example
print(reverse_words("Hello World")) # Output: "World Hello"
|
Breakdown
How It Works:
- The lambda function
reverse_words processes a string s by first splitting it into words. - The
split() method converts the sentence into a list of words. - The slice
[::-1] reverses the list of words. " ".join(...) concatenates the reversed list back into a single string with spaces.
Step-by-Step:
- Splitting the Sentence:
Use s.split() to break the sentence into words. - Reversing the List:
Reverse the list of words using slicing. - Joining the Words:
Combine the reversed words into a sentence with " ".join(). - Result:
The sentence with words in reverse order is produced.
10. Convert List of Strings to Integers
1
2
3
4
| to_int = lambda lst: list(map(int, lst))
# Example
print(to_int(["1", "2", "3"])) # Output: [1, 2, 3]
|
Breakdown
How It Works:
- The lambda function
to_int takes a list of strings lst as input. - The
map(int, lst) function applies the int conversion to each element. - Wrapping the result in
list() converts the map object back into a list of integers.
Step-by-Step:
- Mapping Conversion:
Use map(int, lst) to convert each string in the list to an integer. - List Construction:
Convert the resulting map object into a list. - Result:
A new list of integers is returned.