Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 22, 2022 03:08 pm GMT

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)

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")

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)

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)

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 == 0else "Odd number" for i in range(8)]print(lis)

Answer this question in comments.


Original Link: https://dev.to/jindalkeshav82/practice-questions-on-list-comprehension-1e5c

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To