lmurdock12
lmurdock12

Reputation: 1021

Why isn't .reverse() working?

I am trying to take a sentence and split that sentence, reverse it, and print it to the screen.

I am having trouble understanding how .reverse() works? When I do something like:

test = ['This','is','a','test']
new_test = test.reverse()
print(new_test)

When I run this I am getting None, why is this? How can I make .reverse() work?

Here is my final code:

sentence = input("What is your sentence? ")
split_sentence = sentence.split().reverse()
for word in sentence:
    print(word,end='')

Upvotes: 2

Views: 2239

Answers (5)

bala chandar
bala chandar

Reputation: 1

list1 = [1,2,3,4,5,6]
print([ele for ele in reversed(list1)])

OUTPUT:

[6,5,4,3,2,1]

Upvotes: 0

Mahesh Karia
Mahesh Karia

Reputation: 2055

reverse() function performs in place reversal of a list and that's reason you're getting None in new_test list. You can use following snippet to have reversed list.

from copy import deepcopy

test = ['This','is','a','test']
new_test = deepcopy(test)
print(new_test)
new_test.reverse()
print(new_test)

output:

['This', 'is', 'a', 'test']
['test', 'a', 'is', 'This']

Upvotes: 3

jhpratt
jhpratt

Reputation: 7130

reverse() operates in place, and doesn't return a new array. If you want to use a copy, you'll need to do the following:

arr = [1, 2, 3, 4, 5]
copy = arr.copy() # omit this if you don't want a new list
copy.reverse()
# copy now contains [5, 4, 3, 2, 1]
# arr still contains [1, 2, 3, 4, 5]

Upvotes: 6

Mureinik
Mureinik

Reputation: 311228

reverse() reverses a list in-place, and returns None. Just print your original list:

test = ['This','is','a','test']
test.reverse() # In-place!
print(test)

Upvotes: 5

akash karothiya
akash karothiya

Reputation: 5950

You can use slicing

test = ['This','is','a','test']
>>> print(test[::-1])
['test', 'a', 'is', 'This']

Upvotes: 4

Related Questions