Computer Science
What will be the output of the following Python code ?
lst1 = "hello"
lst2 = list((x.upper(), len(x)) for x in lst1)
print(lst2)
- [('H', 1), ('E', 1), ('L',1), ('L',1), ('O', 1)]
- [('HELLO', 5)]
- [('H',5), ('E', 5), ('L',5), ('L',5), ('O', 5)]
- Syntax error
Linear Lists
1 Like
Answer
[('H', 1), ('E', 1), ('L',1), ('L',1), ('O', 1)]
Reason —
lst1 = "hello"
— This line initializes a string variablelst1
with the value "hello".lst2 = list((x.upper(), len(x)) for x in lst1)
— This line is a list comprehension, which iterates over each characterx
in the stringlst1
. For each characterx
, it creates a tuple containing two elements:
(a) The uppercase version of the characterx
, obtained using theupper()
method.
(b) The length of the characterx
, obtained using thelen()
function.
These tuples are collected into a list, which is assigned to the variablelst2
.print(lst2)
— This line prints the listlst2
.
Answered By
1 Like
Related Questions
Is Ragged list a nested list ?
What will be the output of the following Python code ?
a = [10,23,56,[78, 10]] b = list(a) a[3][0] += 17 print(b)
- [10, 23, 71, [95, 10]]
- [10, 23, 56, [78, 25]]
- [10, 23, 56, [95, 10]]
- [10, 34, 71, [78, 10]]
What will be the output of the following Python code ?
lst = [3, 4, 6, 1, 2] lst[1:2] = [7,8] print(lst)
- [3, 7, 8, 6, 1, 2]
- Syntax error
- [3, [7, 8], 6, 1, 2]
- [3, 4, 6, 7, 8]
What will be the output of the following Python code snippet ?
k = [print(i) for i in my_string if i not in "aeiou"]
- prints all the vowels in my_string
- prints all the consonants in my_string
- prints all characters of my_string that aren't vowels
- prints only on executing print(k)