close

How to get every first element in 2 dimensional list

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to get every first element in 2 dimensional list in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to get every first element in 2 dimensional list?

  1. How to get every first element in 2 dimensional list?

    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]

  2. get every first element in 2 dimensional list

    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]

Method 1

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]

Method 2

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]

Edit: zip object is not subscriptable. It need to be converted to list to access as list:

column = list(zip(*row))

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read