Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing a list using slice notation

in the following example:

foo = ['red', 'white', 'blue', 1, 2, 3] 

where: foo[0:6:1] will print all elements in foo. However, foo[6:0:-1] will omit the 1st or 0th element.

>>> foo[6:0:-1] [3, 2, 1, 'blue', 'white'] 

I understand that I can use foo.reverse() or foo[::-1] to print the list in reverse, but I'm trying to understand why foo[6:0:-1] doesn't print the entire list?

like image 481
user737079 Avatar asked May 03 '11 23:05

user737079


People also ask

What does [- 1 :] mean in Python?

Python also allows you to index from the end of the list using a negative number, where [-1] returns the last element. This is super-useful since it means you don't have to programmatically find out the length of the iterable in order to work with elements at the end of it.

How do you slice backwards in Python?

Create a slice that starts at the end of the string, and moves backwards. In this particular example, the slice statement [::-1] means start at the end of the string and end at position 0, move with the step -1 , negative one, which means one step backwards.

Which slice operation will reverse the list in Python?

You can reverse a list in Python using the built-in reverse() or reversed() methods. These methods will reverse the list without creating a new list. Python reverse() and reversed() will reverse the elements in the original list object. Reversing a list is a common part of any programming language.

What does [:- 1 in Python do?

Why Use [:-1] The slice operator [:-1] is a shorthand expression to produce a result from an original string or list variable to remove the last character in a string or last element in a list. The slice operation will not mutate (permanently change) the original string or list variable.


2 Answers

Slice notation in short:

[ <first element to include> : <first element to exclude> : <step> ] 

If you want to include the first element when reversing a list, leave the middle element empty, like this:

foo[::-1] 

You can also find some good information about Python slices in general here:
Explain Python's slice notation

like image 173
Andrew Clark Avatar answered Sep 18 '22 17:09

Andrew Clark


If you are having trouble remembering slice notation, you could try doing the Hokey Cokey:

[In: Out: Shake it all about]

[First element to include: First element to leave out: The step to use]

YMMV

like image 24
Captain Lepton Avatar answered Sep 18 '22 17:09

Captain Lepton