Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reverse() does not work on a Python literal?

Tags:

python

Why doesn't this work in Python?

>>> print [0,1,0,1,1,0,1,1,1,0,1,1,1,1,0].reverse() 
None

I expected to get back the list in reverse order.

like image 911
Aleksandr Levchuk Avatar asked Jul 26 '11 08:07

Aleksandr Levchuk


People also ask

Can you reverse in Python?

You can reverse a string in Python using slicing or the reversed() method. A recursive function that reads each character in a string and reverses the entire string is another common way to reverse a string. There is no function explicitly designed to reverse a string.

How does reverse work in Python?

Python List reverse() is an inbuilt method in the Python programming language that reverses objects of the List in place i.e. it doesn't use any extra space but it just modifies the original list.

What is the wrong way to reverse a list in Python?

Every list in Python has a built-in reverse() method you can call to reverse the contents of the list object in-place. Reversing the list in-place means won't create a new list and copy the existing elements to it in reverse order. Instead, it directly modifies the original list object.

How do you reverse a element in Python?

In Python, there is a built-in function called reverse() that is used to reverse the list. This is a simple and quick way to reverse a list that requires little memory. Syntax- list_name. reverse() Here, list_name means you have to write the name of the list which has to be reversed.


1 Answers

>>> a = [3, 4, 5]
>>> print a.reverse()
None
>>> a
[5, 4, 3]
>>>

It's because reverse() does not return the list, rather it reverses the list in place. So the return value of a.reverse() is None which is shown in the print.

like image 164
taskinoor Avatar answered Oct 15 '22 03:10

taskinoor