I am having my first ever Python exam this Monday, and am naturally very nervous! I am currently going through some old exams and this question appeared:
“What result of the following code will appear on the terminal?”
x = [1, "two", 3, "four", 5, "six"] (x+x)[x[2]:x[2] + x[4]][(x+x)[8]]
I tested it, and the answer is 1. However, I can’t seem to wrap my head around why. If anyone would be kind enough to explain the logic here that would be much appreciated!
Advertisement
Answer
>>> x = [1, "two", 3, "four", 5, "six"] >>> (x+x)[x[2]:x[2] + x[4]][(x+x)[8]] 1
Now this can be broken into steps. First we concatenate x with itself, this will produce a new list:
>>> (x+x) [1, 'two', 3, 'four', 5, 'six', 1, 'two', 3, 'four', 5, 'six']
This is by the way the same as x * 2 or 2 * x.
Now, naturally, x[2] is the element at index 2, or 3, and x[4] is 5. x[2] + x[4] evaluates to 8.
Now we slice the concatenated list by elements [3:8], getting indices 3…7 of the original:
>>> (x+x)[x[2]:x[2] + x[4]] ['four', 5, 'six', 1, 'two']
And finally we index this list again using (x + x)[8] – this will return the element at index 8 of the concatenated list which is 3. This is used to select the element at index 3 of the list from the previous step which is the number 1 between six and two…