Send
Close Add comments:
(status displays here)
Got it! This site "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
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.
See Python list comprehensions for more on list comprehensions.
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).
list1 is the entire list.
list1[e1] is the element at position e1 (from the start of the list).
list1[-e1] is the element at position e1 from the end of the list.
list1[e1:] is the list starting at position e1 to the end of the list
list1[:e2] is the list from the beginning to the position (before) e2.
list1[e1:e2] is the list from the position e1 to the position (before) e2.
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.
list1[::-1] returns the list with the order of the elements reversed.
list1[::2] returns the list with every other element included.
list1[::-2] returns the list with every other element included from the end of the list
Here is the Python code [#6]
Here is the output of the Python code.
5. End of page