KnowledgeBoat Logo

Computer Science

What does each of the following expressions evaluate to? Suppose that L is the list
["These", ["are", "a", "few", "words"], "that", "we", "will", "use"].

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

Python List Manipulation

38 Likes

Answer

  1. ['are', 'few']
  2. True
  3. ['These', 'are', 'a', 'few', 'words']
  4. ['that', 'will']
  5. True

Explanation

  1. L[1] returns ["are", "a", "few", "words"]. L[1][0::2] returns a slice of ["are", "a", "few", "words"] starting at index 0 covering every alternate element till the end of the list. So, final output is ['are', 'few'].
  2. L[1][0] is "are". As "a" is present in "are" so output is True.
  3. L[:1] return L[0] i.e. ["These"]. L[1] returns ["are", "a", "few", "words"]. + operator adds the two in a single list to give the final output as ['These', 'are', 'a', 'few', 'words'].
  4. L[2::2] returns a slice of L starting at index 2 covering every alternate element till the end of the list. So, final output is ['that', 'will'].
  5. L[1] is ["are", "a", "few", "words"]. L[2][2] is "a". As "a" is present in L[1] so output is True.

Answered By

14 Likes


Related Questions