Related Articles

# Output of python program | Set 11(Lists)

• Difficulty Level : Medium
• Last Updated : 07 Nov, 2017

Pre-requisite: List in python

1) What is the output of the following program?

 `data ``=` `[``2``, ``3``, ``9``]``temp ``=` `[[x ``for` `x ``in``[data]] ``for` `x ``in` `range``(``3``)]``print` `(temp)`

a) [[[2, 3, 9]], [[2, 3, 9]], [[2, 3, 9]]]
b) [[2, 3, 9], [2, 3, 9], [2, 3, 9]]
c) [[[2, 3, 9]], [[2, 3, 9]]]
d) None of these

Ans. (a)
Explanation: [x for x in[data] returns a new list copying the values in the list data and the outer for statement prints the newly created list 3 times.

2) What is the output of the following program?

 `data ``=` `[x ``for` `x ``in` `range``(``5``)]``temp ``=` `[x ``for` `x ``in` `range``(``7``) ``if` `x ``in` `data ``and` `x``%``2``=``=``0``]``print``(temp)`

a) [0, 2, 4, 6]
b) [0, 2, 4]
c) [0, 1, 2, 3, 4, 5]
d) Runtime error

Ans. (b)
Explanation: The is statement checks whether the value lies in list data and if it does whether it’s divisible by 2. It does so for x in (0, 7).

3) What is the output of the following program?

 `temp ``=` `[``'Geeks'``, ``'for'``, ``'Geeks'``]``arr ``=` `[i[``0``].upper() ``for` `i ``in` `temp]``print``(arr)`

a) [‘G’, ‘F’, ‘G’]
b) [‘GEEKS’]
c) [‘GEEKS’, ‘FOR’, ‘GEEKS’]
d) Compilation error

Ans. (a)
Explanation: The variable i is used to iterate over each element in list temp. i represent the character at 0th index of i and .upper() function is used to capitalize the character present at i.

4) Whats is the output of the following program?

 `temp ``=` `'Geeks 22536 for 445 Geeks'``data ``=` `[x ``for` `x ``in` `(``int``(x) ``for` `x ``in` `temp ``if` `x.isdigit()) ``if` `x``%``2` `=``=` `0``]``print``(data)`

a) [2, 2, 6, 4, 4]
b) Compilation error
c) Runtime error
d) [‘2’, ‘2’, ‘5’, ‘3’, ‘6’, ‘4’, ‘4’, ‘5’]

Ans. (a)
Explanation: This is an example of nested list comprehension. The inner list created contains a list of integer in temp. The outer list only procures those x which are a multiple of 2.

5) What is the output of the following program?

 `data ``=` `[x ``for` `x ``in` `(x ``for` `x ``in` `'Geeks 22966 for Geeks'` `if` `x.isdigit()) ``if` `(x ``in` `([x ``for` `x ``in` `range``(``20``)]))]``print``(data)`

a) [2, 2, 9, 6, 6]
b) []
c) Compilation error
d) Runtime error

Ans. (b)
Explanation: Since here x have not been converted to int, the condition in the if statement fails and therefore, the list remains empty.

This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.