What is list comprehension in Python, and how does it work?
List comprehension in Python is a simple way to create/generate lists.
It allows you to generate a new list by applying an expression, loop or condation, all in a single line of code.
What is the Syntex for list comprehension :
lst = [expression for item in iterable if condition]
- expression: This is the value that will be added to the new list.
- item: The variable representing each element in the iterable (like a list or a range).
- iterable: The collection you want to loop through (e.g., a list, tuple, or range).
- condition (optional): An optional filter to include only certain items in the new list.
Example for List comprehension:
Let’s create a list to generate numbers from 0 to 10 using list comprehension:
lst = [x for x in range(11)]
print(lst)
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Example2 :- Let’s create a list of squares of even numbers from 0 to 10 using list comprehension:
lst = [x**2 for x in range(11) if x % 2 == 0]
print(lst)
Output:
[0, 4, 16, 36, 64, 100]
List Comprehension questions and answers designed for interview purposes with examples.
Question 1: Create a list comprehension that triples all elements in the list [2, 4, 6, 8].
Answer:
tripled = [x * 3 for x in [2, 4, 6, 8]]
print(tripled)
Output:
[6, 12, 18, 24]
Question 2: Use list comprehension to filter words containing the substring "eye" from the list ["theagleye", "eye", "watcher", "the eagle"].
Answer:
contains_eye = [word for word in ["theagleye", "eye", "watcher", "the eagle"] if "eye" in word]
print(contains_eye)
Output:
['theagleye', 'eye']
Question 3: Using list comprehension, generate a list of squares of numbers from 1 to 10, but only include numbers greater than 5.
Answer:
x = [x**2 for x in range(1, 11) if x > 5]
print(x)
Output:
[36, 49, 64, 81, 100]
Question 4: Using list comprehension, filter the list ["theagleye", "eagle", "watch", "tower"] to only include words that have an odd number of characters.
Answer:
odd_length_words = [word for word in ["theagleye", "eagle", "watch", "tower"] if len(word) % 2 != 0]
print(odd_length_words)
Output:
['theagleye', 'eagle', 'watch', 'tower']
Question 5: Write a list comprehension that generates a list of numbers divisible by both 3 and 4 in the range from 1 to 50.
Answer:
div_by_3_and_4 = [x for x in range(1, 51) if x % 3 == 0 and x % 4 == 0]
print(div_by_3_and_4)
Output:
[12, 24, 36, 48]
Question 6: Create a list comprehension to reverse all words in ["theagleye", "eagle", "eye"].
Answer:
reversed_words = [word[::-1] for word in ["theagleye", "eagle", "eye"]]
print(reversed_words)
Output:
['eyelgaeht', 'elgae', 'eye']
Question 7: Using list comprehension, extract all vowels from the string "the eagle eye watches theagleye".
Answer:
vowels = [char for char in "the eagle eye watches theagleye" if char in "aeiou"]
print(vowels)
Output:
['e', 'e', 'a', 'e', 'e', 'e', 'a', 'e', 'e', 'a', 'e', 'e']
Question 8: Create a list comprehension to generate the first 10 numbers of the Fibonacci sequence.
Answer:
fibonacci = [0, 1]
[fibonacci.append(fibonacci[-1] + fibonacci[-2]) for _ in range(8)]
print(fibonacci)
Output:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Question 9: Using list comprehension, extract the first letter of each word from the list ["theagleye", "watcher", "eagle"].
Answer:
first_letters = [word[0] for word in ["theagleye", "watcher", "eagle"]]
print(first_letters)
Output:
['t', 'w', 'e']
Question 10: Write a list comprehension to create a list of numbers that are both even and multiples of 5 in the range from 1 to 100.
Answer:
even_and_multiple_of_5 = [x for x in range(1, 101) if x % 2 == 0 and x % 5 == 0]
print(even_and_multiple_of_5)
Output:
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Question 11: Create a list comprehension that filters all words from ["theagleye", "eagle", "eye"] that have the letter "g" in them.
Answer:
words_with_g = [word for word in ["theagleye", "eagle", "eye"] if 'g' in word]
print(words_with_g)
Output:
['theagleye', 'eagle']
Question 12: Write a list comprehension that takes the string "123 theagleye 456" and extracts all numbers as integers.
Answer:
numbers = [int(char) for char in "123 theagleye 456" if char.isdigit()]
print(numbers)
Output:
[1, 2, 3, 4, 5, 6]
Question 13: Generate a list of all combinations of characters from the strings "the" and "eye" using list comprehension.
Answer:
combinations = [a + b for a in "the" for b in "eye"]
print(combinations)
Output:
['te', 'ty', 'te', 'he', 'hy', 'he', 'ee', 'ey', 'ee']
Question 14: Using list comprehension, generate a list that repeats the string "eagle" three times for each word in ["theagleye", "watcher", "eye"].
Answer:
repeated_eagle = ["eagle" * 3 for _ in ["theagleye", "watcher", "eye"]]
print(repeated_eagle)
Output:
['eagleeagleeagle', 'eagleeagleeagle', 'eagleeagleeagle']
Question 15: Create a list comprehension that counts how many times the letter "e" appears in each word of the list ["theagleye", "eagle", "watcher"].
Answer:
e_counts = [word.count('e') for word in ["theagleye", "eagle", "watcher"]]
print(e_counts)
Output:
[3, 2, 1]
Question 16: Using list comprehension, remove all spaces from the string "the eagle eye".
Answer:
no_spaces = ''.join([char for char in "the eagle eye" if char != ' '])
print(no_spaces)
Output:
theeagleeye
Question 17: Write a list comprehension that filters numbers that are prime in the range from 1 to 20.
Answer:
primes = [x for x in range(2, 21) if all(x % y != 0 for y in range(2, x))]
print(primes)
Output:
[2, 3, 5, 7, 11, 13, 17, 19]
Question 18: Using list comprehension, replace all occurrences of "eye" with "sight" in the list ["the eagle eye", "theagleye", "watcher"].
Answer:
replaced = [word.replace('eye', 'sight') for word in ["the eagle eye", "theagleye", "watcher"]]
print(replaced)
Output:
['the eagle sight', 'theaglsight', 'watcher']
Question 19: Create a list comprehension that generates a list of all distinct letters in the word "theagleye".
Answer:
distinct_letters = list(set([char for char in "theagleye"]))
print(distinct_letters)
Output:
['t', 'a', 'l', 'h', 'g', 'y', 'e']
Question 20: Generate a list comprehension that finds the product of corresponding elements from two lists [1, 2, 3] and [4, 5, 6].
Answer:
products = [x * y for x, y in zip([1, 2, 3], [4, 5, 6])]
print(products)
Output:
[4, 10, 18]
Question 21: How does list comprehension make Python code easier to read and faster? Give an example.
Answer: List comprehension makes code shorter and clearer. Instead of writing many lines to create a list, you can do it in one line. It's also faster because Python handles it better in the background.
# Traditional for loop
squares = []
for x in range(1, 6):
squares.append(x**2)
# List comprehension (more readable and concise)
squares = [x**2 for x in range(1, 6)]
print(squares)
Output:
[1, 4, 9, 16, 25]
Question 22: What is a common mistake people make when using list comprehension?
Answer: A common mistake is making the expression too complicated. It's easy to try to do too much in one line, which can make the code hard to understand. It's better to keep it simple.
# Complicated list comprehension
result = [x**2 if x % 2 == 0 else x**3 for x in range(10) if x > 5]
print(result)
Output:
[36, 343, 64, 729]
Question 23: When should you avoid using list comprehension?
Answer: You should avoid using list comprehension when the logic is complex or when you need multiple steps to create the list. If it's hard to read, using a regular loop is better.
# Not easy to read
result = [x * 2 if x > 10 else x + 5 for x in range(20)]
print(result)
Output:
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 22, 24, 26, 28, 30, 32, 34, 36, 38]
Question 24: Can you explain how list comprehension handles multiple lists?
Answer: List comprehension can work with multiple lists using the zip function. This lets you combine elements from different lists in one go.
# Two lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
# Using zip with list comprehension
result = [x + y for x, y in zip(list1, list2)]
print(result)
Output:
[5, 7, 9]
Tags:
Leave a comment
You must be logged in to post a comment.