0

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?

2
  • try print(last_names[::-1]) Commented Nov 11, 2014 at 16:42
  • I'm just guessing about usage here, but including a space after each last name is not good. The space belongs to last name usage, not definition! Commented Nov 11, 2014 at 16:50

2 Answers 2

2

.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].

Sign up to request clarification or add additional context in comments.

Comments

1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.