Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

Help me out here...

    ERROR : AttributeError: 'map' object has no attribute 'sort'
like image 705
Sushil Chaskar Avatar asked Oct 18 '15 14:10

Sushil Chaskar


1 Answers

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(' ')))
like image 125
Mazdak Avatar answered Sep 19 '22 08:09

Mazdak