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

Sushil Chaskar picture Sushil Chaskar · Oct 18, 2015 · Viewed 21.5k times · Source

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)

Help me out here...

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

Answer

Kasravnd picture Kasravnd · Oct 18, 2015

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(' ')))