104

I have a list containing version strings, such as things:

versions_list = ["1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2"]

I would like to sort it, so the result would be something like this:

versions_list = ["1.0.0", "1.0.2", "1.0.12", "1.1.2", "1.3.3"]

The order of precedence for the digits should obviously be from left to right, and it should be descending. So 1.2.3 comes before 2.2.3 and 2.2.2 comes before 2.2.3.

How do I do this in Python?

tripleee
  • 175,061
  • 34
  • 275
  • 318
Zack
  • 2,021
  • 4
  • 18
  • 19

6 Answers6

179

You can also use distutils.version module of standard library:

from distutils.version import StrictVersion
versions = ["1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2"]
versions.sort(key=StrictVersion)

Gives you:

['1.0.0', '1.0.2', '1.0.12', '1.1.2', '1.3.3']

It can also handle versions with pre-release tags, for example:

versions = ["1.1", "1.1b1", "1.1a1"]
versions.sort(key=StrictVersion)

Gives you:

["1.1a1", "1.1b1", "1.1"]

Documentation: https://github.com/python/cpython/blob/3.2/Lib/distutils/version.py#L101

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
andreypopp
  • 6,887
  • 5
  • 26
  • 26
  • 1
    Seems more pythonic then Eli's solution. – Vojta Rylko Apr 04 '10 at 11:41
  • 29
    There's also distutils.version.LooseVersion which is a little more forgiving with version numbers that end in letters ['1.0b', '1.0.2-final'], etc. or whatnot - I prefer this version since StrictVersion seems to be more oriented towards Python distutils specific version strings, LooseVersion caters to a wider swath of potential version strings you'll see in the wild. – synthesizerpatel Jul 24 '11 at 06:32
  • `StrictVersion` does not handle versions such as '9.20.00.0': invalid version number is returned. I'm wondering if, however, this is because the actual version is indicated as `u'9.20.00.0'` ...??? Maybe this needs to be decoded to UTF-8. – IAbstract May 07 '15 at 20:22
  • 4
    In case you need more freedom, you could use distutils.version.LooseVersion over StrictVersion. See http://epydoc.sourceforge.net/stdlib/distutils.version.LooseVersion-class.html – ferdy Feb 18 '16 at 09:21
  • Unfortunately, even `LooseVersion` doesn't work if you have `['0.1.0', 'latest']` like you might get back from a docker registry. For that, I use the [natsort](https://stackoverflow.com/a/31425911/117471) answer on this page. – Bruno Bronosky Dec 19 '17 at 00:17
  • what is the diff between using `key=StrictVersion` to `key=LooseVersion`? – A. Man Dec 28 '20 at 09:20
  • 5
    Note that `distutils` is getting deprecated, see https://www.python.org/dev/peps/pep-0632/. It mentions using `packaging` instead (which is third-party). – Peter Lithammer Apr 26 '21 at 13:16
  • @PeterLithammer: Yes, you can do `versions.sort(key=packaging.version.Version)`. Also see [PEP440](https://www.python.org/dev/peps/pep-0440/). – djvg Dec 07 '21 at 14:30
  • 1
    @djvg Your code returns `None`. This one works: `import packaging; versions = ["1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2"]; sorted(versions, key=packaging.version.Version)` – Dr_Zaszuś May 19 '23 at 11:25
  • 2
    @Dr_Zaszuś It is expected to return `None`, because it sorts in-place. See [sorting-basics](https://docs.python.org/3/howto/sorting.html#sorting-basics). – djvg May 19 '23 at 11:42
119

Split each version string to compare it as a list of integers:

versions_list.sort(key=lambda s: map(int, s.split('.')))

Gives, for your list:

['1.0.0', '1.0.2', '1.0.12', '1.1.2', '1.3.3']

In Python3 map no longer returns a list, So we need to wrap it in a list call.

versions_list.sort(key=lambda s: list(map(int, s.split('.'))))

The alternative to map here is a list comprehension. See this post for more on list comprehensions.

versions_list.sort(key=lambda s: [int(u) for u in s.split('.')])
Community
  • 1
  • 1
Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
  • For the regular expression solution you would just replace the s with the expression that returns the group that you want. For example: lambda s: map(int, re.search(myre, s).groups[0].split('.')) – Andrew Cox Apr 04 '10 at 10:09
  • 5
    This is pure elegance. – Balthazar Rouberol Sep 16 '13 at 20:20
  • Sort return None, but list is sorted. – themadmax Apr 12 '16 at 08:11
  • 5
    That key function will not work in Python 3 because `map` returns an iterator in Python 3, not a list. But this will work in both versions: `key=lambda s: [int(u) for u in s.split('.')])`. – PM 2Ring Jun 02 '16 at 21:04
  • 2
    Recommend you assume the reader is using Python 3 and show python 2 as the exception, if that's even needed. – macetw Apr 19 '18 at 19:04
  • How does the `s:` part of `.sort()` work? (I'm confused about where the `s` comes from) – ioannes Aug 26 '20 at 17:53
  • This does not make sense to me. This seems like magic. This works but does not seem obviously logical. Maybe this is because I do not use `map` or `lambda` or specify a `key` to the sort or sorted methods often. It is like each list element is split on the dot into a separate list and sorted. Wow! – user3808269 Oct 29 '21 at 22:27
  • it works only with numbers, but it doesn't work if the version has hyphens. In this case, if I have he string "0-40" in he version I get: invalid literal for int() with base 10: '0-40' – maxadamo May 01 '22 at 01:15
  • This is the only version which works correctly. The others (natsort, and packaging.version) both sort the micro versions alphabetically, leading to incorrect sort order. – Colin Jul 03 '23 at 12:47
31

natsort proposes "natural sorting"; wich works very intuitively (in Python 3)

from natsort import natsorted
versions = ["1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2"]
natsorted(versions)

gives

['1.0.0', '1.0.2', '1.0.12', '1.1.2', '1.3.3']

but it works as well on complete package names with version number:

versions = ['version-1.9', 'version-2.0', 'version-1.11', 'version-1.10']
natsorted(versions)

gives

['version-1.9', 'version-1.10', 'version-1.11', 'version-2.0']
Chris Maes
  • 35,025
  • 12
  • 111
  • 136
  • 1
    how to implement this with list of dictionary ? i.e. [{'env': 'REE', 'version': 'API-1.1.12'}, {'env': 'REE', 'version': 'API-1.2.0'}] I want to implement sorting based on version key. – Vijaysinh Parmar Sep 25 '19 at 05:27
8

I think meanwhile, one would use packaging.version for that.

Example:

from packaging.version import parse as parseVersion
versions = ['3.1', '0.7.1', '3.4.1', '0.7.7', '0.7.2', '3.3', '3.4.0', '0.7'
            '0.7.5', '0.7.6', '3.0', '3.3.1', '0.7.3', '3.2', '0.7.4']
versions.sort(key = parseVersion)

Output:

['0.7', '0.7.1', '0.7.2', '0.7.3', '0.7.4', '0.7.5', '0.7.6',
 '0.7.7', '3.0', '3.1', '3.2', '3.3', '3.3.1', '3.4.0', '3.4.1']
Tobias Leupold
  • 1,512
  • 1
  • 16
  • 41
  • Unfortunately [v22.0](https://github.com/pypa/packaging/releases/tag/22.0) deprecated `LegacyVersion` so it now only supports strict versions strings (no arbitrary strings), but before that it was my ideal solution. – Silveri Apr 03 '23 at 06:58
1

I also solved this question using Python, although my version does some extra things, here is my code:

def answer(l):
    list1 = [] # this is the list for the nested strings
    for x in l:
        list1.append(x.split("."))
    list2 = [] # this is the same list as list one except everything  is an integer in order for proper sorting
    for y in list1:
        y = list(map(int, y))
        list2.append(y)
    list3 = sorted(list2) #this is the sorted list of of list 2
    FinalList = [] # this is the list that converts everything back to the way it was
    for a in list3:
        a = '.'.join(str(z) for z in a)
        FinalList.append(a)
    return FinalList

For versions there exist three things; Major, Minor, and the revision. What this does is that it organises it so that '1' will come before '1.0' which will come before '1.0.0'. Also, another plus, no need to import any libraries incase you don't have them, and it works with old versions of Python, this one was specifically meant for Version 2.7.6. Anyway, here are a few examples:

Inputs:
    (string list) l = ["1.1.2", "1.0", "1.3.3", "1.0.12", "1.0.2"]
Output:
    (string list) ["1.0", "1.0.2", "1.0.12", "1.1.2", "1.3.3"]

Inputs:
    (string list) l = ["1.11", "2.0.0", "1.2", "2", "0.1", "1.2.1", "1.1.1", "2.0"]
Output:
    (string list) ["0.1", "1.1.1", "1.2", "1.2.1", "1.11", "2", "2.0", "2.0.0"]

If you have any questions, just comment on the answer!

Kye
  • 4,279
  • 3
  • 21
  • 49
-1

I have an answer to this question. Unlike other codes, my code is bit lengthy and has more time and space complexity.

The advantage of my code is that, this code just uses built in functions and could be of a great exercise to practice and master looping concept for the beginners.

x=["1.11.0","2.0.0","1.2.1","1.1.1",'1.2.0']                    #Driver List 
le=len(x)                                                       #Length of the given driver list
x2=[]                                                           #list to store the values of x after splitting 
mapping=[]                                                      #list to store the values after type converstion 
map1=[]                                                         #list to store the values after sorting 
final=[]                                                        #list to store the final value after concatenation 

#Loop for splitting the given values with respect to '.'

for i in x:
    y=i.split('.')
    x2.append(y)
#print(x2)

#Loop for mapping the string value to integer value. This conversion overcomes the issue we have 
#With simple sorting technique as given in the question, and helps us in sorting the versions in our desired format

for i in range(0,le,1):
    mapped=list(map(int,x2[i]))                                 # mapped is a return value for the map()
    mapping.append(mapped)                                      # mapped value which is now a int, is appended to mapping array
#print(mapping)

mapping.sort()                                                  #Sorts the elements present in mapping array


#Loop to re-convert all the sorted integer value to string type

for i in mapping:
    mapp=list(map(str,i))                                       # mapp is a return value for the map()
    map1.append(mapp)                                           # mapp is now a str, gets appended to map1 array
#print(mapp)

#Loop to cancatenate the str values in mapp array with the '.'
#This converts the individual str type values in mapp array to its original form, like those in DriverList 

for i in range(0,le,1):
    for j in range(0,1,1):
        h=map1[i][j]+"."+map1[i][j+1]+"."+map1[i][j+2]
        final.append(h)

#Loop to Print the desired answer

for i in final:
    print(i,end='  ')



#For Better understanding of this program, uncomment the print statements in line 13, 21, 31.

The Output for the above code will be like:

1.1.1  1.2.0  1.2.1  1.11.0  2.0.0

The above is the sorted versions given in the driver list. Hope my code is clear. Pls feel free to ask any doubts if you have in comment section

DrinkandDerive
  • 67
  • 1
  • 1
  • 7