Python List Comprehension Exercise Questions
Below are two exercise questions on Python list comprehension. We have covered basic list comprehension code to find the cube of numbers and code to find the length of a word using list comprehension and the len() function.
Q1. Cube of numbers exercise question using list comprehension
Python
numbers = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] cube = [number * * 3 for number in numbers] print (cube) |
Output
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
Q2. Finding word length exercise question using list comprehension
Python
words = [ "apple" , "banana" , "cherry" , "orange" ] word_lengths = [ len (word) for word in words] print (word_lengths) |
Output
[5, 6, 6, 6]
Python – List Comprehension
A Python list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element in the Python list.
Example:
Python
numbers = [ 12 , 13 , 14 ,] doubled = [x * 2 for x in numbers] print (doubled) |
Output
[24, 26, 28]