Search code examples
pythonpython-3.xsortingiterable

Getting attribute error: 'map' object has no attribute 'sort'


I am trying to sort array in increasing order. But getting the following error for the code:

a = []
a = map(int, input().split(' '))
a.sort()
print(a)

Error:

AttributeError: 'map' object has no attribute 'sort'


Solution

  • In python 3 map doesn't return a list. Instead, it returns an iterator object and since sort is an attribute of list object, you're getting an attribute error.

    If you want to sort the result in-place, you need to convert it to list first (which is not recommended).

    a = list(map(int, input().split(' ')))
    a.sort()
    

    However, as a better approach, you could use sorted function which accepts an iterable and return a sorted list and then reassign the result to the original name (is recommended):

    a = sorted(map(int, input().split(' ')))