List comprehension in Python
List comprehensions in Python are a powerful and concise way to create new lists based on existing iterables (like lists, tuples, strings, etc.). They offer a more compact alternative to traditional for loops with append.
Syntax:
new_list = [expression for item in iterable [if condition]]
- expression: This is what you want to do with each item in the iterable. It can be a simple variable representing the item, a calculation, a function call, or anything that evaluates to a value.
- item: This represents the variable that takes on the value of each item in the iterable as you loop through it. Think of it as a temporary variable for each iteration.
- iterable: This is the data source you're iterating over, like a list, tuple, string, or any object that can return its elements one at a time.
- condition (optional): This is an optional
if
clause that acts as a filter. Only items that meet the condition will be included in the new list.
Here are some examples to illustrate different uses of list comprehensions:
Example 1: Adding some items from one list to another
# both methods do the same thing
# Method 1
a = [2, 5, 7, 8, 12, 56, 44, 34, 33, 89, 68, 99]
b = []
for item in a:
if item%2 == 0:
b.append(item)
print(b)
# Method 2
b = [ i for i in a if i%2==0 ]
print(b)
Example 2: Squaring elements
numbers = [1, 2, 3, 4]
squared_numbers = [number * number for number in numbers]
print(squared_numbers) # Output: [1, 4, 9, 16]
Example 3: Filtering elements
fruits = ["apple", "banana", "cherry", "orange"]
filtered_fruits = [fruit for fruit in fruits if fruit != "apple"]
print(filtered_fruits) # Output: ["banana", "cherry", "orange"]
Example 4: Using lambda functions:
temperatures = [15, 28, 10, 22]
is_hot = [temp for temp in temperatures if lambda t: t > 25(temp)]
print(is_hot) # Output: [True, True, False, True]
A point to be noted is, list comprehensions are not always the best option. If your logic gets too complex, it might be better to use a traditional for loop for better readability.
Comments
Post a Comment
Write something to CodeWithAbdur!