[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

This question is related to python list multidimensional-array

The answer is


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.


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))

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


Compared the 3 methods

  1. 2D list: 5.323603868484497 seconds
  2. Numpy library : 0.3201274871826172 seconds
  3. Zip (Thanks to Joran Beasley) : 0.12395167350769043 seconds
D2_list=[list(range(100))]*100
t1=time.time()
for i in range(10**5):
    for j in range(10):
        b=[k[j] for k in D2_list]
D2_list_time=time.time()-t1

array=np.array(D2_list)
t1=time.time()        
for i in range(10**5):
    for j in range(10):
        b=array[:,j]        
Numpy_time=time.time()-t1

D2_trans = list(zip(*D2_list)) 
t1=time.time()        
for i in range(10**5):
    for j in range(10):
        b=D2_trans[j]
Zip_time=time.time()-t1

print ('2D List:',D2_list_time)
print ('Numpy:',Numpy_time)
print ('Zip:',Zip_time)

The Zip method works best. It was quite useful when I had to do some column wise processes for mapreduce jobs in the cluster servers where numpy was not installed.


If you have access to numpy,

import numpy as np
a_transposed = a.T
# Get first row
print(a_transposed[0])

The benefit of this method is that if you want the "second" element in a 2d list, all you have to do now is a_transposed[1]. The a_transposed object is already computed, so you do not need to recalculate.

Description

Finding the first element in a 2-D list can be rephrased as find the first column in the 2d list. Because your data structure is a list of rows, an easy way of sampling the value at the first index in every row is just by transposing the matrix and sampling the first list.


You could use this:

a = ((4.0, 4, 4.0), (3.0, 3, 3.6), (3.5, 6, 4.8))
a = np.array(a)
a[:,0]
returns >>> array([4. , 3. , 3.5])

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to multidimensional-array

what does numpy ndarray shape do? len() of a numpy array in python What is the purpose of meshgrid in Python / NumPy? Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray Typescript - multidimensional array initialization How to get every first element in 2 dimensional list How does numpy.newaxis work and when to use it? How to count the occurrence of certain item in an ndarray? Iterate through 2 dimensional array Selecting specific rows and columns from NumPy array