Possible Duplicate:
Python program to split a list into two lists with alternating elements
I have a list like this:
list1 = [blah, 3, haha, 2, pointer, 1, poop, fire]
The output I want is:
list = [3, 2, 1, fire]
So what I want is to make a list of even elements of the former list. I tried using a for
statement and tried to delete 2nth element while appending them to the list, but it didn't work out:
count = 0 for a in list1: list2.append(a) if count % 2 = = 1: list2.pop(count) print list2
Any suggestions?
To split a list into n parts in Python, use the numpy. array_split() function. The np. split() function splits the array into multiple sub-arrays.
The easiest way to split list into equal sized chunks is to use a slice operator successively and shifting initial and final position by a fixed number.
Step 1 : create a user input list. Step 2 : take two empty list one for odd and another for even. Step 3 : then traverse each element in the main list. Step 4 : every element is divided by 2, if remainder is 0 then it's even number and add to the even list, otherwise its odd number and add to the odd list.
You can use list slicing. The following snippet will do.
list1 = ['blah', 3, 'haha', 2, 'pointer', 1, 'poop', 'fire'] listOdd = list1[1::2] # Elements from list1 starting from 1 iterating by 2 listEven = list1[::2] # Elements from list1 starting from 0 iterating by 2 print listOdd print listEven
Output
[3, 2, 1, 'fire'] ['blah', 'haha', 'pointer', 'poop']
This should give you what you need - sampling a list at regular intervals from an offset 0 or 1:
>>> a = ['blah', 3,'haha', 2, 'pointer', 1, 'poop', 'fire'] >>> a[0:][::2] # even ['blah', 'haha', 'pointer', 'poop'] >>> a[1:][::2] # odd [3, 2, 1, 'fire']
Note that in the examples above, the first slice operation (a[1:]
) demonstrates the selection of all elements from desired start index, whereas the second slice operation (a[::2]
) demonstrates how to select every other item in the list.
A more idiomatic and efficient slice operation combines the two into one, namely a[::2]
(0
can be omitted) and a[1::2]
, which avoids the unnecessary list copy and should be used in production code, as others have pointed out in the comments.
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