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"].
- L[1][0::2]
- "a" in L[1][0]
- L[:1] + L[1]
- L[2::2]
- L[2][2] in L[1]
Python List Manipulation
38 Likes
Answer
- ['are', 'few']
- True
- ['These', 'are', 'a', 'few', 'words']
- ['that', 'will']
- True
Explanation
- 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'].
- L[1][0] is "are". As "a" is present in "are" so output is True.
- 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'].
- 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'].
- 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