I use reverse, but it returns me None, can you help?
ls = [1,2,3,4,5,6,7,8,9]
print('List = ',ls)
print('Reversed List = ',ls.reverse())
this is result:
('List = ', [1, 2, 3, 4, 5, 6, 7, 8, 9])
('Reversed List = ', None)
I use reverse, but it returns me None, can you help?
ls = [1,2,3,4,5,6,7,8,9]
print('List = ',ls)
print('Reversed List = ',ls.reverse())
this is result:
('List = ', [1, 2, 3, 4, 5, 6, 7, 8, 9])
('Reversed List = ', None)
Because reverse
does not return a list, it mutates the list in place. A method with no return always returns None
. Try:
ls = [1,2,3,4,5,6,7,8,9]
print('List = ',ls)
ls.reverse()
print('Reversed List = ',ls)
Alternatively you could use a step value with slice notation. This also has the effect of not mutating the input list:
ls = [1,2,3,4,5,6,7,8,9]
print('List = ',ls)
print('Reversed List = ',ls[::-1])
reverse
method does the operations "in-place", so you need to do:
ls = [1,2,3,4,5,6,7,8,9]
print('List = ',ls)
ls.reverse()
print('Reversed List = ', ls)
Or use reversed
that isn't "in-place":
ls = [1,2,3,4,5,6,7,8,9]
print('List = ',ls)
print('Reversed List = ', list(reversed(ls)))
Or a cool slicing method:
ls = [1,2,3,4,5,6,7,8,9]
print('List = ',ls)
print('Reversed List = ', ls[::-1])