Send Close Add comments: (status displays here)
Got it!  This site "www.robinsnyder.com" uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.  Note: This appears on each machine/browser from which this site is accessed.
Python: Slices
by RS  admin@robinsnyder.com : 1024 x 640


1. Python: Slices
How could one get the last element of the following list?

The solution, coming from, say, C or Java would be similar to the following.

And this does work, but is not Pythonic. Here is the Python code [#3]

Here is the output of the Python code.


2. Slices
Python has a nice way to access parts of lists - individual and contiguous elements - using what is called a slice.

A negative index into a list is considered and index from the end of the list.

Here is the Python code [#5]

Here is the output of the Python code.

But the slice idea goes further - including parts of lists, list comprehensions, etc. The general form of a slice, by example, is as follows, where parts can be omitted as in the examples (that follow).
start:stop:index


3. Slices with start and/or stop
The general form of a slice, by example, is as follows (where expressions e1 and e2 evaluate to nonnegative integer values). Note that a string is considered a list of characters and the slice idea can be used with strings as well.

4. Index parameter
The index parameter allows one to iterate through the list in the selection process - as in a list comprehension. Here is the Python code [#6]

Here is the output of the Python code.




5. End of page

by RS  admin@robinsnyder.com : 1024 x 640