Python How to get every first element in 2 Dimensional List

I have a list like this :

a = ((4.0, 4, 4.0), (3.0, 3, 3.6), (3.5, 6, 4.8))

I want an outcome like this (EVERY first element in the list) :

4.0, 3.0, 3.5

I tried a[::1][0], but it doesn't work

I'm just start learning Python weeks ago. Python version = 2.7.9

Answers


You can get the index [0] from each element in a list comprehension

>>> [i[0] for i in a]
[4.0, 3.0, 3.5]

Also just to be pedantic, you don't have a list of list, you have a tuple of tuple.


use zip

columns = zip(*rows) #transpose rows to columns
print columns[0] #print the first column
#you can also do more with the columns
print columns[1] # or print the second column
columns.append([7,7,7]) #add a new column to the end
backToRows = zip(*columns) # now we are back to rows with a new column
print backToRows

you can also use numpy

a = numpy.array(a)
print a[:,0]

You can get it like

[ x[0] for x in a]

which will return a list of the first element of each list in a


Try using

for i in a :
  print(i[0])

i represents individual row in a.So,i[0] represnts the 1st element of each row.


Need Your Help

Animated Icon for ActionItem

android android-animation actionbarsherlock

I have been searching everywhere for a proper solution to my problem and I can't seem to find one yet. I have an ActionBar (ActionBarSherlock) with a menu that is inflated from an XML file and that...

Converting a string to and from Base 64

python-3.x base64

I am trying to write two programs one that converts a string to base64 and then another that takes a base64 encoded string and converts it back to a string.