One way is using the range() function, such that it starts at the first odd index, 1 , and has a step value of 2 , so that it returns the odd indices 1, 3, 5, ... . Another way to obtain the odd indices of a list is using list comprehension, in which you can use a condition that will only include the odd indices.
Yes, you can:
l = L[1::2]
And this is all. The result will contain the elements placed on the following positions (0
-based, so first element is at position 0
, second at 1
etc.):
1, 3, 5
so the result (actual numbers) will be:
2, 4, 6
The [1::2]
at the end is just a notation for list slicing. Usually it is in the following form:
some_list[start:stop:step]
If we omitted start
, the default (0
) would be used. So the first element (at position 0
, because the indexes are 0
-based) would be selected. In this case the second element will be selected.
Because the second element is omitted, the default is being used (the end of the list). So the list is being iterated from the second element to the end.
We also provided third argument (step
) which is 2
. Which means that one element will be selected, the next will be skipped, and so on...
So, to sum up, in this case [1::2]
means:
step=2
, so we are skipping one, as a contrary to step=1
which is default),EDIT: @PreetKukreti gave a link for another explanation on Python's list slicing notation. See here: Explain Python's slice notation
enumerate()
In your code, you explicitly create and increase the counter. In Python this is not necessary, as you can enumerate through some iterable using enumerate()
:
for count, i in enumerate(L):
if count % 2 == 1:
l.append(i)
The above serves exactly the same purpose as the code you were using:
count = 0
for i in L:
if count % 2 == 1:
l.append(i)
count += 1
More on emulating for
loops with counter in Python: Accessing the index in Python 'for' loops
For the odd positions, you probably want:
>>>> list_ = list(range(10))
>>>> print list_[1::2]
[1, 3, 5, 7, 9]
>>>>
I like List comprehensions because of their Math (Set) syntax. So how about this:
L = [1, 2, 3, 4, 5, 6, 7]
odd_numbers = [y for x,y in enumerate(L) if x%2 != 0]
even_numbers = [y for x,y in enumerate(L) if x%2 == 0]
Basically, if you enumerate over a list, you'll get the index x
and the value y
. What I'm doing here is putting the value y
into the output list (even or odd) and using the index x
to find out if that point is odd (x%2 != 0
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With