I'm quite new to python, though I have a lot of experience with bash. I have a file that consists of a single column of numbers, and I would like to find the largest number in the list. I tried to do so with the following code:
i = 0
with open('jan14.nSets.txt','r') as data:
for num in data:
if num > i:
i = num
print(i)
where jan14.nSets.txt is the following:
12
80
46
51
0
64
37
9
270
23
132
133
16
6
18
23
32
75
2
9
6
74
44
41
56
17
9
4
8
5
3
27
1
3
42
23
58
118
100
185
85
63
220
38
163
27
198
Rather than 270, I receive 9 as an output, and I do not understand why this is the case. I know that there are builtins for this, but I would like to know why this doesn't work to help me understand the language. I am using python2.7
num
is a string, not a number. Turn it into an integer first usingint()
:You are comparing text, so it is ordered lexicographically,
'9' > '80'
because the ASCII character'9'
has a higher codepoint than'8'
:After the
'9'
line, all other lines either have an initial digit that is smaller than'9'
, or the line is equal.You could use the
max()
function instead, provided you first usemap()
to turn all lines into integers:or use a generator expression (in Python 2, more memory efficient than
map()
):Both pull in all lines from
data
, map the lines to integers, and determine the maximum value from those.