KnowledgeBoat Logo

Computer Science

What does each of the following expressions evaluate to? Suppose that T is the tuple containing :
("These", ["are" , "a", "few", "words"] , "that", "we", "will" , "use")

  1. T[1][0: :2]
  2. "a" in T[1][0]
  3. T[:1] + [1]
  4. T[2::2]
  5. T[2][2] in T[1]

Python Tuples

7 Likes

Answer

The given expressions evaluate to the following:

  1. ['are', 'few']
  2. True
  3. TypeError: can only concatenate tuple (not "list") to tuple
  4. ('that', 'will')
  5. True
Explanation
  1. T[1] represents first element of tuple i.e., the list ["are" , "a", "few", "words"]. [0 : : 2] creates a list slice starting from element at index zero of the list to the last element including every 2nd element (i.e., skipping one element in between).
  2. "in" operator is used to check elements presence in a sequence. T[1] represents the list ["are" , "a", "few", "words"]. T[1][0] represents the string "are". Since "a" is present in "are", it returns true.
  3. T[:1] is a tuple where as [1] is a list. They both can not be concatenated with each other.
  4. T[2::2] creates a tuple slice starting from element at index two of the tuple to the last element including every 2nd element (i.e., skipping one element in between).
  5. T[2] represents the string "that". T[2][2] represents third letter of "that" i.e., "a". T[1] represents the list ["are" , "a", "few", "words"]. Since "a" is present in the list, the in operator returns True.

Answered By

3 Likes


Related Questions