Python Forum
Error using min() function on a list
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Error using min() function on a list
#1
Hello everybody.

I am trying to find the max and min values of the first two columns of a matrix. I have written the following code

f = open('XdataTXT.txt','r')
linesX=f.readlines()
X_column_number = 0
positionX=[]
Y_column_number = 1
positionY=[]
for x in linesX:
    positionX.append(x.split()[X_column_number])
    positionY.append(x.split()[Y_column_number])
f.close()
print(positionX)
print(max(positionX))
print(min(positionX))
However, my output does not look like what it should. The max(positionX) is returned as it should, but the min(positionX) doesn't, since the output is
Output:
-1.0000000e+00
but the smallest element is -75. Aditionally, if the same is done using the second column, positionY, the both outputs look as they should.

Can someone tell me what am I doing wrong?

Thanks.
Reply
#2
Well the thing is that you probably want to do the max and min over a list of number right?
what you are building there are list of strings. For the max function it will work kind of since in comparison of strings a 7 is still greater than a 5 (alphabetically). For the min function the 1 (of -1.0000000e+00) is less than the 7 (of -75) therefore it is the minimum. So the script works right, but not like you want it to. try converting the strings you get out of the file to float:
for x in linesX:
    positionX.append(float(x.split()[X_column_number]))
    positionY.append(float(x.split()[Y_column_number]))
Be careful though if you got an empty string from somewhere (it can happen) you get a problem converting
Reply
#3
(Jan-29-2020, 04:18 PM)ThiefOfTime Wrote: Well the thing is that you probably want to do the max and min over a list of number right?
what you are building there are list of strings. For the max function it will work kind of since in comparison of strings a 7 is still greater than a 5 (alphabetically). For the min function the 1 (of -1.0000000e+00) is less than the 7 (of -75) therefore it is the minimum. So the script works right, but not like you want it to. try converting the strings you get out of the file to float:
for x in linesX:
    positionX.append(float(x.split()[X_column_number]))
    positionY.append(float(x.split()[Y_column_number]))
Be careful though if you got an empty string from somewhere (it can happen) you get a problem converting

Yes that was exactly the problem. Thanks.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  I created a function that generate a list but the list is empty in a new .py file mrhopeedu 2 2,332 Oct-12-2019, 08:02 PM
Last Post: mrhopeedu
  Error in using the output of one function in another function (beginner) MadsPJ 6 5,059 Mar-13-2017, 03:06 PM
Last Post: MadsPJ

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020