Getting attribute error: 'map' object does not have 'sort' attribute

I am trying to sort an array in ascending order. But excess error for code:

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

Help me here.

+5
source share
1 answer

In Python 3, map does not return a list. Instead, it returns an iterator object, and since sort is an attribute of a list object, you get an attribute error.

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

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

However, as a better approach, you can use the sorted function, which takes an iterable and returns a sorted list, and then reassigns the result to its original name (recommended):

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

Source: https://habr.com/ru/post/1233967/


All Articles