Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - str() function completely alters list

Below is a code to generate the products of any two 3-digits numbers

integers_list = [(i * x)    for i in range(100,1000)   for x in range(100,1000)]
string_list = (map(str, integers_list))

integers_list.sort()
string_list.sort()

print integers_list[-10:-1]
print string_list[-10:-1]

gives:

[995004, 995004, 995006, 995006, 996003, 996003, 996004, 997002, 997002]
['99994', '99994', '99996', '99996', '99997', '99997', '99999', '99999', '99999']

This also occurs if I instead use str(i * x) in the list comprehension.

The numbers in the strings list aren't even possible given the expression.

Why is this happening, and what can I do to fix it?


2 Answers

Strings sort in a different order than integers. 9800 is greater than 990, but '9800' is less than '990'.

like image 192
Mark Ransom Avatar answered Mar 20 '26 04:03

Mark Ransom


As Mark Ransom pointed out, the reason is because sorting strings is done lexicographically. To make the sorting process sort by integer value, do this:

string_list.sort(key=int)
integers_list.sort(key=int)
like image 33
smac89 Avatar answered Mar 20 '26 05:03

smac89