KnowledgeBoat Logo

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)
  1. [('H', 1), ('E', 1), ('L',1), ('L',1), ('O', 1)]
  2. [('HELLO', 5)]
  3. [('H',5), ('E', 5), ('L',5), ('L',5), ('O', 5)]
  4. Syntax error

Linear Lists

3 Likes

Answer

[('H', 1), ('E', 1), ('L',1), ('L',1), ('O', 1)]

Reason —

  1. lst1 = "hello" — This line initializes a string variable lst1 with the value "hello".
  2. lst2 = list((x.upper(), len(x)) for x in lst1) — This line is a list comprehension, which iterates over each character x in the string lst1. For each character x, it creates a tuple containing two elements:
    (a) The uppercase version of the character x, obtained using the upper() method.
    (b) The length of the character x, obtained using the len() function.
    These tuples are collected into a list, which is assigned to the variable lst2.
  3. print(lst2) — This line prints the list lst2.

Answered By

3 Likes


Related Questions