DEV Community

Keshav Jindal
Keshav Jindal

Posted on • Updated on

Practice questions on List Comprehension.

1.

names = ["aman", "vikas", "vivek", "sandeep", "manik"]
new_names = [2*x for x in names if "a" in x]
print(new_names)

Enter fullscreen mode Exit fullscreen mode

Explanation-
Iteration1:
1st item is going to be picked by new_names that is,"aman" and "a" is there in the item, and condition became true.
Iteration2:
2nd item that is "vikas" will be picked out and "a" letter will be checked, and condition became true.
Iteration3:
3rd item that is "vivek" will be picked out and "a" letter will be checked, and condition became false.
Iteration5:
5th and the last item that is "manik" will be picked out and "a" letter will be checked, and condition became true.
final output-['amanaman', 'vikasvikas', 'sandeepsandeep', 'manikmanik']
2.

for x in "data":
 if x == "t":
  break
 print(x)
print("The end")

Enter fullscreen mode Exit fullscreen mode

Explanation-
Iteration 1:
x=’d’ ,condition become true and loop get to connected.
if ‘d’==’t’ condition became false and print(x)=d
Iteration 2:
x=’a’ condition become true and machine jumps into the body of loop.
if ‘a’ == ‘y’ condition is false and print(x)= a
Iteration 3:
x=’t’ condition is true
if ‘t’==’t’ if condition is true and break executes and machine
jumps outside the loop
print(‘The end’) = The end
Final output d
a
The end
3.

numbers = [i*10 for i in range(1, 6)]
print(numbers)
Enter fullscreen mode Exit fullscreen mode

Explanation-
Iteration1:
i=1 condition became true and it will be multiplied by 10 and output become 10
Iteration2:
i=2 condition became true and it will be multiplied by 20 and output become 20
Iteration2:
i=5 condition became true and it will be multiplied by 50 and output become 50
Final output:[10, 20, 30, 40, 50]
4.

List = [character for character in 'Geeks 4 Geeks!']
print(List)
Enter fullscreen mode Exit fullscreen mode

Explanation-
Iteration1:
character=G ,condition became true and "G" will be executed.
Iteration2:
character=e ,condition became true and "e" will be executed.
Iteration14:
character=! ,condition became true and "!" will be executed.
Final output:
['G', 'e', 'e', 'k', 's', ' ', '4', ' ', 'G', 'e', 'e', 'k', 's', '!']
5.

lis = ["Even number" if i % 2 == 0
else "Odd number" for i in range(8)]
print(lis)
Enter fullscreen mode Exit fullscreen mode

Answer this question in comments.

Top comments (1)

Collapse
 
sandeeparora14 profile image
Sandeep

Keep it up. Very informative