List comprehension is a compact and readable way to create lists in Python. The syntax might feel tricky at first, but once understood, it becomes a powerful tool for writing cleaner code.
[expression for item in iterable if condition]
[x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]
range(10): This generates numbers from 0 to 9.for x in range(10): Loop through each number in the range and name it x.if x % 2 == 0: Only include numbers that are divisible by 2 (even).x: Since no transformation is needed, we store each qualifying number as-is.[x**2 for x in [1, 2, 3, 4]] # [1, 4, 9, 16]
[1, 2, 3, 4]: This is the original list.for x in ...: We're looping over each number and calling it x.x**2: We square each number and add the result to the list.[s for s in ["apple", "banana", "apricot"] if s.startswith("a")] # ['apple', 'apricot']
["apple", "banana", "apricot"]: This is the original list.for s in ...: We're looping over each item in the list and naming each item s.if s.startswith("a"): This filters the items — we only keep s if it starts with "a".s at the beginning means each matching item will be included in the result list as-is.[[i * j for j in range(1, 4)] for i in range(1, 4)] # [[1, 2, 3], [2, 4, 6], [3, 6, 9]]
range(1, 4): Gives us 1, 2, 3.for j in range(1, 4) → generates [i*j for j in range(1, 4)] for a fixed i.for i in range(1, 4) → applies the inner loop three times.i * j: For each pair (i, j), multiply the numbers.i multiplied by each j.Problem: Return a sorted list of elements divisible by a given divisor. If none found, return [-1].
arr = [5, 9, 7, 10]
divisor = 5
result = sorted([x for x in arr if x % divisor == 0])
if not result:
result = [-1]
print(result) # [5, 10]
[x for x in arr if x % divisor == 0]: Filters out elements from arr that are divisible by divisor.sorted(...): Sorts the filtered result in ascending order.if not result: If the filtered list is empty, replace it with [-1].print(result): Displays the final list.List<Integer> result = new ArrayList<>();
for (int n : arr) {
if (n % divisor == 0) result.add(n);
}
if (result.isEmpty()) result.add(-1);
Collections.sort(result);
for loop.if.Use them wisely, especially for one-liners or simple filters and transformations!