1. Introduction
List comprehension is a concise and memory-efficient way to create and manipulate lists in Python. It's a syntactic feature that allows lists to be built from other lists by applying expressions to each element.
Definition
List comprehension is a way to construct lists in a very clear and concise way. A typical list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses.
2. Program Steps
1. Define a list to work with.
2. Use list comprehension to create a new list based on the defined list.
3. Apply conditions or operations to each element during the list creation.
4. Print the resulting list.
3. Code Program
# Step 1: Define a list of numbers
numbers = [1, 2, 3, 4, 5]
# Step 2: Use list comprehension to create a new list of squares
squares = [number ** 2 for number in numbers]
# Step 3: Print the list of squares
print(f"Squares of numbers: {squares}")
# Example of list comprehension with a condition
# Step 2: Use list comprehension to create a new list of even numbers
evens = [number for number in numbers if number % 2 == 0]
# Step 3: Print the list of even numbers
print(f"Even numbers: {evens}")
# Example of list comprehension with multiple conditions
# Step 2: Use list comprehension for numbers divisible by 2 and not by 5
evens_not_fives = [number for number in numbers if number % 2 == 0 if number % 5 != 0]
# Step 3: Print the resulting list
print(f"Even numbers not divisible by 5: {evens_not_fives}")
Output:
Squares of numbers: [1, 4, 9, 16, 25] Even numbers: [2, 4] Even numbers not divisible by 5: [2, 4]
Explanation:
1. numbers is the original list of integers from 1 to 5.
2. squares is created using list comprehension that squares each number in numbers.
3. The first print statement outputs the list squares, showing the squares of each integer in numbers.
4. evens is created using list comprehension with a condition (if number % 2 == 0) to filter only even numbers.
5. The second print statement displays evens, listing only the even integers from numbers.
6. evens_not_fives is created using list comprehension with multiple conditions to filter out numbers divisible by 5.
7. The third print statement shows evens_not_fives, which includes numbers from numbers that are even and not divisible by 5.
Comments
Post a Comment
Leave Comment