Anvith
Anvith

Reputation: 507

split a list into two consisting of desired elements using python

I have a list as shown below :

[[[77.56913757324219, 12.975883483886719], [77.5671615600586, 12.976168632507324], [77.5680160522461, 12.980805397033691], [77.56996154785156, 12.980448722839355], [77.56913757324219, 12.975883483886719]]]

How can i split this into two lists such that one list contains all the elements in odd places and the other consists of elements at even places. The output I am expecting to get is:

list1 = [[[77.56913757324219, 12.975883483886719],[77.5680160522461, 12.980805397033691],[77.56913757324219, 12.975883483886719]]]

and

list2 = [[[77.5671615600586, 12.976168632507324],[77.56996154785156, 12.980448722839355]]]

I looking for a solution using python.

Thank you.

Upvotes: 0

Views: 63

Answers (2)

sshashank124
sshashank124

Reputation: 32189

You can simply do:

list1 = list[::2]

AND

list2 = list[1::2]

These both use list splicing and the third specified parameter, [::2] specifies a step value of 2

Examples

>>> a = [1,2,3,4,5,6,7]

>>> print a[::2]
[1,3,5,7]

>>> print a[1::2]
[2,4,6]

I know that in your example, the list is nested within other lists but I'll let you figure that out. Hope that helps.

Upvotes: 1

perreal
perreal

Reputation: 97938

biglist = [[
    [77.56913757324219, 12.975883483886719], [77.5671615600586, 12.976168632507324], 
    [77.5680160522461, 12.980805397033691], [77.56996154785156, 12.980448722839355], 
    [77.56913757324219, 12.975883483886719]
]]

list1 = [ biglist[0][::2] ]
list2 = [ biglist[0][1::2] ]

Upvotes: 1

Related Questions