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.
len(myLines)
will give you the number of objects inside that list no matter if they are lists, dicts or strings. – Delrosarioprint myLines
and the reason will be clear. – Tapiacsv
module if you want that to happen. – Teadorlen(myLines)
will be3
regardless of the content of each. Perhaps you have a blank line at the end of the file. Another thing to try is usingopen("filetest.txt", "rt")
because some platforms have multiple characters at the end of each line of a text file which could confusereadlines()
. – Trafficator