0

What is the correct way to print out the biggest number from a list in Python?

lst = ["1.1.3.9", "1.1.3.11", "1.1.3.30", "1.1.3.8", "1.1.2.7"]
print max(lst)

gives me

1.1.3.9

This value is wrong. The max value must be 1.1.3.30.

Please help. Many thanks in advance.

David Jones
  • 4,766
  • 3
  • 32
  • 45
Son
  • 11
  • 1
  • 1
    Your list items are strings, not numbers. As a result, max has to use lexicographic comparisons, under which rules 1.1.3.30 sorts before 1.1.3.9 (3 comes before 9) and the last item in your list ends up being the value you're getting. You'll need to invest some time in somehow parsing your strings in order to achieve the desired result. – g.d.d.c Jan 27 '18 at 02:37
  • Issue here is that `1.1.3.9` is equivalent to `1.1.3.90` – jimmu Jan 27 '18 at 02:37
  • 2
    @Alexander Version strings? Those look like IP addresses to me. – cs95 Jan 27 '18 at 02:39
  • `>>> from distutils.version import LooseVersion` `>>> lst = ["1.1.3.9", "1.1.3.11", "1.1.3.30", "1.1.3.8", "1.1.2.7"]` `>>> max(lst, key=LooseVersion)` – jamylak Jan 27 '18 at 02:40
  • @Son Are those version strings or IP addresses that you are comparing. Would a max IP address make any sense? I presumed no, hence why I am assuming version numbers. – Alexander Jan 27 '18 at 02:40
  • @Alexander While it semantically feels odd to use a version comparing tool to compare IP addresses, it still works... So, the dupe closure is correct IMO x) – cs95 Jan 27 '18 at 02:41
  • If you trying to find the string with the highest number after the last the `.`, you can try this: `max(lst, key = lambda x: int(x.split('.')[-1]))` – RoadRunner Jan 27 '18 at 02:46
  • Additionally, If these are IP addresses, then they are IPv4. – RoadRunner Jan 27 '18 at 02:53

0 Answers0