0

Currently I am learning Python, and I hope someone can kindly help me. I tried to use sort() to sort a specific list ascending, but when I try this example its outputs is wrong.

Number_list[9,5,13]
Number_list.sort()
print Number_list

The result that I have is : ['13', '5', '9']

and it should be : ['5', '9', '13']

I am trying to write program that show the maximum odd number, and i write the code as following:

Number_list = []
print "Enter first number:"
Number_list.append (raw_input());
print "Enter second number:"
Number_list.append (raw_input());
print "Enter third number:"
Number_list.append (raw_input());
Number_list.sort()
if int(Number_list[2]) % 2 != 0 :
     print Number_list[2]
elif int(Number_list[1]) %2 != 0:
     print Number_list[1]
elif int(Number_list[0]) % 2 != 0:
     print Number_list[0]
else:
    print "There is no Odd number"
1
  • 1
    Are you trying to assign Number_list to the list [9,5,13] in your first line? Did you forget =? Commented Apr 18, 2016 at 12:08

2 Answers 2

3

Looks like your list is a list of strings and not a list of numbers. Is your list defined like this?

NumberList = ['9', '5', '13']

Update:

From your updated code snippet we see how you fill your list:

Number_list.append(raw_input())

You must know that in Python 2, raw_input returns the user input as string and does not parse it to a numeric type.

That means you are getting a list of strings, as I said. We can also see that you want to continue operating on numbers and not on strings, so it's the easiest to just convert the input to integer numbers before appending them to the list:

Number_list.append(int(raw_input()))

That way we get a list of numbers and both the sorting and your calculations in the second half of your code will work as expected.


If we sort that list, it will sort the string content inside alphabetically according to the ASCII codes of the characters. And '1' has of course a lower code than '5' or '9' and therefore '13' is the first element of the result.

You obviously want to sort the list numerically, so you need to either directly fill the list with numbers which was probably intended, or if there's a special reason why the list has to be filled with strings, you need to specify a key function that converts the elements to numbers.

  • Option 1 (list of numbers):

    Number_list = [9, 5, 13]
    Number_list.sort()
    print Number_list
    # output: [5, 9, 13]
    
  • Option 2 (list of strings, but with sort key):

    Number_list = ['9', '5', '13']
    Number_list.sort(key=int)
    print Number_list
    # output: ['5', '9', '13']
    
Sign up to request clarification or add additional context in comments.

7 Comments

i am trying to Write a program that examines three variables—x, y, and z and prints the largest odd number among them. If none of them are odd, i should print a message to that effect. my code was as following:
Number_list = [] print "Enter first number:" Number_list.append (raw_input()); print "Enter second number:" Number_list.append (raw_input()); print "Enter third number:" Number_list.append (raw_input()); Number_list.sort() print Number_list if int(Number_list[2]) % 2 != 0 : print Number_list[2] elif int(Number_list[1]) %2 != 0: print Number_list[1] elif int(Number_list[0]) % 2 != 0: print Number_list[0] else: print "There is no Odd number"
@Alaa Please do not dump your code in a comment, this destroys the formatting and makes it useless. Please edit your question instead and paste it there. Then delete this comment again. Thanks!
@Alaa As I assumed, you field the list with strings (Python 2's raw_input returns the input as string!). See my edit to find out how you have to fill your list instead to get a list of numbers that behaves the way you expect. Also don't forget to accept this answer if it helped you by clicking the grey tick symbol on the left of it. Thank you.
it was really helpful, thank you so much. i already accept this answer
|
1

First, there's a SyntaxError or a TypeError in Number_list[9,5,13]. You probably meant Number_list = [9,5,13].

raw_input() returns a string; not a digit. "13" is a string, 13 without the quotes is an integer. Strings are different from integers and don't support the same methods (mainly maths). However, as Byte Commander also pointed out, all characters also have an ASCII representation; e.g. "A" is 65, the string representation of 1 ("1") is 49, etc. You can see these codes by using the ord() method; e.g. ord("A").

When you sort a list of strings, I believe Python looks at the first character of each string, converts it to its ASCII integer code and sorts it accordingly. Look what happens to the list of strings below:

>>> n = ["1000", "2", "3"]
>>> n.sort()
>>> n
['1000', '2', '3']
>>>

We just sorted a list and still 1000 is smaller than 2 and 3!? This is clearly not true for integers but because our list contains strings, Python does something like this when we call sort():

>>> n = ["1000", "2", "3"]

# get the ASCII code of the first character of every string
>>> n_ascii_codes = [ord(x[0]) for x in n]

# "1" -> 49 (ignoring 000 in 1000), 2 -> 50, 3 -> 51
>>> n_ascii_codes
[49, 50, 51]
>>>  

To fix your code, convert all strings in your list to integers before you call sort(). E.g. by using a list comprehension. This way you don't have to write int() every time you use raw_input():

...
print "Enter third number:"
Number_list.append (raw_input());

# add this if you want to convert all the strings to integers 
Number_list = [int(x) for x in Number_list]

Number_list.sort()
...

5 Comments

Sorry, but a missing "=" does not explain the observed sort order - it would result in an exception TypeError: list indices must be integers, not tuple!
Number_list = [] print "Enter first number:" Number_list.append (raw_input()); print "Enter second number:" Number_list.append (raw_input()); print "Enter third number:" Number_list.append (raw_input()); Number_list.sort() print Number_list if int(Number_list[2]) % 2 != 0 : print Number_list[2] elif int(Number_list[1]) %2 != 0: print Number_list[1] elif int(Number_list[0]) % 2 != 0: print Number_list[0] else: print "There is no Odd number"
@ByteCommander Ah sorry, I read it too quickly and just assumed OP was getting a TypeError without telling us. Instead, it seems that OP is not posting the code that he/she is actually running (we see a list of integers but OP must be using a list of strings)
@Alaa Could you add the code you posted in your comment to the question? It's much easier to read that way.
Some ASCII codes in the first paragraph are wrong. "A" is 65. Other than that it looks fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.