Andy
Andy

Reputation: 15

Reversing list with strings in python

I have this list,

last_names = [
'Hag ', 'Hag ', 'Basmestad ', 'Grimlavaag ', 'Kleivesund ',
'Fintenes ', 'Svalesand ', 'Molteby ', 'Hegesen ']

and I want to print i reversed, so 'Hegesen' comes first, then ' Molteby' and at the end 'Hag'.

I have tried last_names.reverse(), but that returnes None..

Any help?

Upvotes: 0

Views: 74

Answers (2)

Rafael Barros
Rafael Barros

Reputation: 2881

As stated before, .reverse reverses the list in place, a more pythonic way to reverse a list and return it, is to use reversed:

>>> list(reversed([1,2,3]))
[3, 2, 1]

Upvotes: 1

Fred Foo
Fred Foo

Reputation: 363547

.reverse returns None because it reverses in-place:

>>> last_names = [
... 'Hag ', 'Hag ', 'Basmestad ', 'Grimlavaag ', 'Kleivesund ',
... 'Fintenes ', 'Svalesand ', 'Molteby ', 'Hegesen ']
>>> last_names.reverse()
>>> last_names
['Hegesen ', 'Molteby ', 'Svalesand ', 'Fintenes ', 'Kleivesund ', 'Grimlavaag ', 'Basmestad ', 'Hag ', 'Hag ']

To do this in an expression, do last_names[::-1].

Upvotes: 2

Related Questions