+ 2
How to index an list to show even and odd elements in python?
4 Respuestas
+ 4
You can use a for loop to iterate on a list and you get in each iteration one element. If elements are numbers you can check if they are even or odd. Use modulo division by 2 to see if there is a remainder or not. All elements that have remainder of 0 on this division are even
+ 3
lst = [your_list]
odds = lst[1::2]
evens = lst[0::2]
+ 3
I'm not sure what you mean
l = [4, 17, 25, 22, 1, 14, 6, 2, 1, 23, 4, 13, 21, 15, 3]
list(enumerate(l))
[(0, 4), (1, 17), (2, 25), (3, 22), (4, 1), (5, 14), (6, 6), (7, 2), (8, 1), (9, 23), (10, 4), (11, 13), (12, 21), (13, 15), (14, 3)]
🍌 All elements with an odd index:
[n for index, n in enumerate(l) if index%2] # [17, 22, 14, 2, 23, 13, 15]
🍌 All elements with an odd index:
[n for index, n in enumerate(l) if not index%2] # [4, 25, 1, 6, 1, 4, 21, 3]
🍌 Indices of all odd elements:
[index for index, n in enumerate(l) if n%2] # [1, 2, 4, 8, 9, 11, 12, 13, 14]
🍌 Indices of all even elements:
[index for index, n in enumerate(l) if not n%2] # [0, 3, 5, 6, 7, 10]
+ 2
list comprehensions
l = [1, 2, 3, 4, 5, 6]
even = [i for i in l if i%2 == 0]
odd = [x for x in l if x%2 != 0]