Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Here is a problem for a Python beginner\'s class, so it needs to be simple code.

ID: 3722409 • Letter: H

Question

Here is a problem for a Python beginner's class, so it needs to be simple code.

L = [0, [], [1,2,3,4], [[5],[6,7]], [8,9,10]]

using both, indexing and slicing on L, assemble and print a new list N that contains:

[0,2,3,[5,6],8,10]

To illustrate:

L = [0, [], [1,2,3,4], [[5],[6,7]], [8,9,10]]

N = [ L[2][1:-1], L[-1][2] ]

print N

would print out:

[[2, 3], [10]]

You need to do something similar but end up with [0,2,3,[5,6],8,10] instead.

The best way to work through this is to break the process down in small steps and explain what happens at each step using comments in your code. Use variables to store results of each step and use those variable in the next step(s).

Explanation / Answer

Hello There,

A simple way to achieve is to index all the required elements and group them as a list in the desired format.

PFB screenshot of the same when executed:

-----------------------------------------------------------------------------------

>>> L = [0, [], [1,2,3,4], [[5],[6,7]], [8,9,10]]
>>> X = [L[0], L[2][1], L[2][2], [L[3][0][0], L[3][1][0]], L[4][0], L[4][2]]
>>> print X
[0, 2, 3, [5, 6], 8, 10]
>>>

----------------------------------------------------------------------------

Here is another way to accomplish the same thing:

PFB screenshot of execution:

----------------------------------------

>>> L = [0, [], [1,2,3,4], [[5],[6,7]], [8,9,10]]
>>> A = L[0]
>>> B, C = L[2][1:-1]
>>> D = L[3][0][0]
>>> E = L[3][1][0]
>>> F, G = L[4][0::2]
>>> X = [A, B, C, [D,E], F,G]
>>> print X
[0, 2, 3, [5, 6], 8, 10]
>>>