Q.Select the correct output of the following code: event="G20 Presidency@2023" L=event.split(' ') print(L[::-2]) (A) 'G20' (B) ['Presidency@2023'] (C) ['G20'] (D) 'Presidency@2023'
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →The code first splits the string into a list of words, then uses reverse slicing with a step of -2 to select elements from the end of the list, moving backwards and skipping every other element.
Let's break down this Python code step by step to understand its output. The core concepts here are string splitting and list slicing, both fundamental operations in Python.
First, we have the string event = "G20 Presidency@2023". This string contains two distinct parts separated by a space.
The next line, L = event.split(' '), uses the split() method. This method is called on a string and, when given an argument like ' ' (a space), it divides the string into a list of substrings wherever that delimiter (the space) is found.
In our case, event.split(' ') will take "G20 Presidency@2023" and split it at the space between "G20" and "Presidency@2023".
This operation results in a list: ['G20', 'Presidency@2023']. So, the variable L now holds this list.
If no delimiter is provided to split(), it defaults to splitting by any whitespace (spaces, tabs, newlines) and also handles multiple consecutive whitespaces as a single delimiter, removing empty strings from the result. However, here we explicitly provided a single space ' '.
Finally, we have print(L[::-2]). This is a list slicing operation. List slicing in Python uses the syntax [start:stop:step].
start: The index where the slice begins (inclusive). If omitted, it defaults to the beginning of the list.stop: The index where the slice ends (exclusive). If omitted, it defaults to the end of the list.step: The increment between elements. If omitted, it defaults to1.
In [::-2]:
- Both
startandstopare omitted. - The
stepis-2. A negative step value indicates that the slicing should proceed in reverse order, starting from the end of the list.
Let's apply this to our list L = ['G20', 'Presidency@2023']:
- Since the step is negative, Python starts from the last element of the list. The last element of
Lis'Presidency@2023'. This element is included in the result. - From this position, it moves backwards by 2 steps.
- The index of
'Presidency@2023'is1(or-1when counting from the end). - Moving back 2 steps from index
1would take us to index1 - 2 = -1. This is the same element. …
- The index of
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.