Decision
Yes, you can:
l = L[1::2]
And it's all. The result will contain elements placed at the following positions ( 0 , so the first element is at position 0 , the second at 1 , etc.):
1, 3, 5
therefore, the result (real numbers) will be:
2, 4, 6
Description
[1::2] at the end is just a sign to sort the list. Usually it is in the following form:
some_list[start:stop:step]
If we omit start , the default value ( 0 ) will be used. Thus, the first element will be selected (at position 0 , since the indices are 0 ). In this case, the second item will be selected.
Since the second element is omitted, the default value (end of list) is used. Thus, the list is repeated from the second element to the end .
We also provided the third argument ( step ), which is 2 . This means that one item will be selected, the next will be skipped, and so on ...
So, to summarize, in this case [1::2] means:
- take the second element (which, by the way, is an odd element, if you judge by the index),
- skip one element (because we have
step=2 , so we skip one, as opposed to step=1 , which is the default), - take the next item
- Repeat steps 2.-3. until the end of the list is reached,
EDIT : @PreetKukreti gave a link to another explanation in Python list notation notation. See Here: Explain Python Snippet Notation
Additionally - replacing the counter with enumerate()
In your code, you explicitly create and increment a counter. In Python, this is not necessary, since you can list through some iterative option using enumerate() :
for count, i in enumerate(L): if count % 2 == 1: l.append(i)
The above function is for the same purpose as the code you used:
count = 0 for i in L: if count % 2 == 1: l.append(i) count += 1
Learn more about emulating for loops using a counter in Python: Index access in Python loops for loops