Custom Search

Wednesday, March 13, 2013

python how to find all odd or even numbers from a list without list comprehension

python how to find all odd or even numbers from a list without list comprehension

1)
Example-1
===========

>>>
>>>
>>> lst = range(0, 20)
>>>
>>>
>>> lst
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>>
>>>
#Get All Odd Numbers Starting from index 1 of list lst
>>>
>>>
>>> lst[1::2]
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>>
>>>
#Get Even Numbers Starting from index 2 of list lst
>>>
>>>
>>> lst[2::2]
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
>>>
>>>
#Get All 3rd th element Starting from index 1 of list lst
>>> lst[1::3]
[1, 4, 7, 10, 13, 16, 19]
>>>
>>>
#Get All 3rd th element Starting from index 0 of list lst
>>> lst[::3]
[0, 3, 6, 9, 12, 15, 18]
>>>
>>>
#Get All 3rd th element Starting from index 0 of list lst
>>> lst[0::3]
[0, 3, 6, 9, 12, 15, 18]
>>>

2)
Example-2
===========

>>>
>>>
>>> lst = range(1, 21)
>>>
>>>
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
>>>
>>>
#Get All Odd Numbers Starting from index 0 of list lst
>>> lst[::2]
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>>
>>>
#Get Even Numbers Starting from index 1 of list lst
>>> lst[1::2]
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
>>>
>>>

No comments:

Post a Comment