🌟 Join our Telegram group for exclusive updates! Join Now Get Involved

List Comprehension

List Comprehension in Python

List comprehension is a concise and powerful way to create lists in Python. It allows you to create a new list by specifying the elements you want to include based on a given expression and optional conditions. The syntax for list comprehension is:

new_list = [expression for item in iterable if condition]
  • expression: The expression to be evaluated for each item.
  • item: A variable representing an element from the iterable.
  • iterable: An iterable (e.g., list, tuple, string) that provides the elements.
  • condition (optional): A condition that filters the elements.

Here are some examples of list comprehensions:

# Basic List Comprehension
squares = [x**2 for x in range(5)]
# Output: [0, 1, 4, 9, 16]

# List Comprehension with Condition
even_squares = [x**2 for x in range(10) if x % 2 == 0]
# Output: [0, 4, 16, 36, 64]

# List Comprehension with If-Else
results = ["Even" if x % 2 == 0 else "Odd" for x in range(5)]
# Output: ['Even', 'Odd', 'Even', 'Odd', 'Even']

# Nested List Comprehension
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [item for row in matrix for item in row]
# Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

# List Comprehension with Function
words = ["hello", "world", "python"]
uppercase_lengths = [len(word.upper()) for word in words]
# Output: [5, 5, 6]

List comprehensions are often more readable and concise than traditional for-loops when creating lists. However, it's essential to use them judiciously to maintain readability and avoid overly complex expressions.

Cookies Consent

This website uses cookies to ensure you get the best experience on our website.

Cookies Policy

We employ the use of cookies. By accessing BYTEFOXD9, you agreed to use cookies in agreement with the BYTEFOXD9's Privacy Policy.

Most interactive websites use cookies to let us retrieve the user’s details for each visit. Cookies are used by our website to enable the functionality of certain areas to make it easier for people visiting our website. Some of our affiliate/advertising partners may also use cookies.