Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python reverse list

Tags:

python

I'm trying to reverse a string and using the below code but the resultant reverse list value is None.

The code:

str_a = 'This is stirng' rev_word = str_a.split() rev_word = rev_word.reverse() rev_word = ''.join(rev_word) 

It returns the TypeError. Why?

like image 660
user1050619 Avatar asked Sep 09 '12 02:09

user1050619


People also ask

How do you reverse a list 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.

How do I reverse a list order?

Method 1: Reversing a list using the reversed() and reverse() built-in function. Using the reversed() method and reverse() method, we can reverse the contents of the list object in place i.e., we don't need to create a new list instead we just copy the existing elements to the original list in reverse order.

How do you reverse a list in slicing in Python?

To reverse a list in Python, you can use negative slicing: As you want to slice the whole list, you can omit the start and stop values altogether. To reverse the slicing, specify a negative step value. As you want to include each value in the reversed list, the step size should be -1.


Video Answer


1 Answers

This is my personal favorite way to reverse a string:

stra="This is a string" revword = stra[::-1]  print(revword) #"gnirts a si sihT 

or, if you want to reverse the word order:

revword = " ".join(stra.split()[::-1])  print(revword) #"string a is This" 

:)

like image 66
Sean Johnson Avatar answered Sep 22 '22 18:09

Sean Johnson