Show more list comprehension examples?

QuestionsQuestions8 SkillsProYour First Linux LabNov, 06 2025
0108

Sure! Here are a few more examples of list comprehensions in Python, showcasing different use cases:

1. Filtering Even Numbers

This example creates a new list containing only the even numbers from an original list.

# Original list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# List comprehension to filter even numbers
even_numbers = [x for x in numbers if x % 2 == 0]

# Print the result
print("Even numbers:", even_numbers)

2. Converting Strings to Uppercase

This example converts a list of strings to uppercase.

# Original list of strings
words = ["hello", "world", "python", "is", "great"]

# List comprehension to convert to uppercase
uppercase_words = [word.upper() for word in words]

# Print the result
print("Uppercase words:", uppercase_words)

3. Creating a List of Tuples

This example creates a list of tuples, where each tuple contains a number and its square.

# Original list of numbers
numbers = [1, 2, 3, 4, 5]

# List comprehension to create tuples of (number, square)
number_square_tuples = [(x, x**2) for x in numbers]

# Print the result
print("Number and square tuples:", number_square_tuples)

4. Flattening a Nested List

This example flattens a nested list (a list of lists) into a single list.

# Nested list
nested_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]

# List comprehension to flatten the nested list
flattened_list = [item for sublist in nested_list for item in sublist]

# Print the result
print("Flattened list:", flattened_list)

5. Generating a List of Squares

This example generates a list of squares for numbers from 1 to 10.

# List comprehension to generate squares
squares = [x**2 for x in range(1, 11)]

# Print the result
print("Squares from 1 to 10:", squares)

These examples illustrate the versatility of list comprehensions in Python for creating new lists based on existing ones, filtering data, and transforming elements. If you have any specific scenarios in mind or need further examples, feel free to ask!

0 Comments

no data
Be the first to share your comment!