EN
Python - why is sorted list None?
1 answers
3 points
I am trying to sort a list in Python and it's NoneType, even tho merged
variable (consisting of my_list1
and my_list2
) is 'list'
type.
What is the reason and how can I fix this?
My code:
xxxxxxxxxx
1
my_list1 = [1, 3, 5]
2
my_list2 = [0, 2, 4]
3
4
merged = my_list1 + my_list2 # <--- this is list type
5
print(type(merged)) # <class 'list'>
6
7
result = merged.sort() # <--- this is NoneType
8
print(result) # None
9
print(type(result)) # <class 'NoneType'>
10
1 answer
3 points
The sort()
method is sorting in place and that's why the result is None
.
Don't assign merged
list to the new result
variable, just sort it.
In your case it would be:
xxxxxxxxxx
1
my_list1 = [1, 3, 5]
2
my_list2 = [0, 2, 4]
3
4
merged = my_list1 + my_list2
5
6
# sort merged list
7
merged.sort()
8
9
# print merged list as a result
10
print(merged) # [0, 1, 2, 3, 4, 5]
0 commentsShow commentsAdd comment