tags:

views:

119

answers:

2

I have a little piece of python code in the server script for my website which looks a little bit like this:

console.append([str(x) for x in data])
console.append(str(max(data)))

quite simple, you might think, however the result it's outputting is this:

['3', '12', '3']
3

for some reason python thinks 3 is the max of [3,12,3]!

So am I doing something wrong? Or this is misbehaviour on the part of python?

+1  A: 

I know very little Python, but you are taking the max of strings, which means that '3..' is greater than '1..'.

AraK
+8  A: 

Because the character '3' is higher in the ASCII table than '1'. You are comparing strings, not numbers. If you want to compare the numerically, you need to convert them to numbers. One way is max(data, key=int), but you might want to actually store numbers in the list.

Lukáš Lalinský
Hmm, that's odd, this worked - however it was meant to be a list of integers!
Martin
It can't be a list of integers if you explicitly convert them to strings using `str(x)` :)
Lukáš Lalinský
Yes, but the data list is a list of integers, and then I cast them to strings and append them to the console, that doesn't affect the contents of data... does it?
Martin
No, integers are immutable, it can't change them anyway. You took the integers, created strings that textually represent the integers and added them to the console list. So the console now contains a list of strings. Then you took the maximum value (lexicographically), create a new string with the same value and added it to the list.
Lukáš Lalinský
Oh, sorry, I actually only now realized you are getting the max of `data`. Ignore the previous comment. The behavior means that the list doesn't contain integers as you think.
Lukáš Lalinský
It seems that everything points to something other than a list of integers, I wish I had a strongly typed language ;)
Martin
@Martin: Python IS a strongly-typed language. Strongly-typed or not is nothing to do with your problem. `str()` and `max()` operate as advertised on a wide variety of types. How do you imagine a strongly-typed language would help you in this case?
John Machin