python access second element of list

  • A+
Category:Languages

When I print my list I get something like this

[[6.0, 0.5], [6.1, 1.0], [6.2, 1.5], [6.3, 2.0], [6.4, 2.5], [6.5, 3.0], [6.6, 3.5], [6.7, 4.0], [6.8, 4.5]]

I want to extract first and second elements from above list into separate lists so that I can ask the plt to plot it for me.

So my results should be [6.0,6.1,6.2 ... 6.8] and [0.5,1.0,1.5,2.0 , ... .4.5]

I want to know if we have a cleaner solution than to

for sublist in l:     i=0     for item in sublist:        flat_list.append(item)        break #get first element of each   

 


You can try list indexing:

data = [[6.0, 0.5], [6.1, 1.0], [6.2, 1.5], [6.3, 2.0], [6.4, 2.5], [6.5, 3.0], [6.6, 3.5], [6.7, 4.0], [6.8, 4.5]] d1 = [item[0] for item in data] print d1 d2 = [item[1] for item in data] print d2 

output :

[6.0, 6.1, 6.2, 6.3, 6.4, 6.5, 6.6, 6.7, 6.8] [0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: