Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get length of a list of lists in python

So, if I have a list called myList I use len(myList) to find the number of elements in that list. Fine. But how do I find the number of lists in a list?

text = open("filetest.txt", "r")
myLines = text.readlines()
numLines=len(myLines)
print numLines

The above text file used has 3 lines of 4 elements separated by commas. The variable numLines prints out as '4' not '3'. So, len(myLines) is returning the number of elements in each list not the length of the list of lists.

When I print myLines[0] I get the first list, myLines[1] the second list, etc. But len(myLines) does not show me the number of lists, which should be the same as 'number of lines'.

I need to determine how many lines are being read from the file.

like image 829
user3022562 Avatar asked Nov 22 '13 17:11

user3022562


2 Answers

This saves the data in a list of lists.

text = open("filetest.txt", "r")
data = [ ]
for line in text:
    data.append( line.strip().split() )

print "number of lines ", len(data)
print "number of columns ", len(data[0])

print "element in first row column two ", data[0][1]
like image 104
Javier Castellanos Avatar answered Nov 09 '22 22:11

Javier Castellanos


"The above text file used has 3 lines of 4 elements separated by commas. The variable numLines prints out as '4' not '3'. So, len(myLines) is returning the number of elements in each list not the length of the list of lists."

It sounds like you're reading in a .csv with 3 rows and 4 columns. If this is the case, you can find the number of rows and lines by using the .split() method:

text = open("filetest.txt", "r").read()
myRows = text.split("\n")      #this method tells Python to split your filetest object each time it encounters a line break 
print len(myRows)              #will tell you how many rows you have
for row in myRows:
  myColumns = row.split(",")   #this method will consider each of your rows one at a time. For each of those rows, it will split that row each time it encounters a comma.  
  print len(myColumns)         #will tell you, for each of your rows, how many columns that row contains
like image 20
duhaime Avatar answered Nov 09 '22 21:11

duhaime