Slicing Lists and Tuples in Python: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 3: Line 3:
* [[Python_Language_Tuple#Slices|Tuples]]
* [[Python_Language_Tuple#Slices|Tuples]]
=Overview=
=Overview=
A sub-sequence of a list can be extracted with a slice. The slice <code>[<start-index>:<end-index>:<step>]</code> specified the index of the last element, and the index of the first element '''not included''' in slice, and the step. The step is optional, the default value is 1.
<syntaxhighlight lang='py'>
l = ['a', 'b', 'c', 'd', 'e', 'f']
assert ['a', 'b', 'c', 'd', 'e', 'f'] == l[:] # starts from the beginning and ends after the end of the list
assert ['c', 'd'] == l[2:4]
assert ['c'] == l[2:4:2]
</syntaxhighlight>
The step can be negative, which means the slice starts at the end and goes from right to left.
<syntaxhighlight lang='py'>
l = ['a', 'b', 'c', 'd', 'e', 'f']
assert ['f', 'e', 'd', 'c', 'b', 'a'] == l[::-1]
</syntaxhighlight>
<code>[:]</code> creates a copy of the list.
<syntaxhighlight lang='py'>
l = ['a', 'b', 'c']
l2 = l[:]
l2[0] = 'x'
assert ['a', 'b', 'c'] == l
assert ['x', 'b', 'c'] == l2
</syntaxhighlight>
Remove the last element of the list:
<syntaxhighlight lang='py'>
l = ['a', 'b', 'c']
l2 = l[:-1]
assert ['a', 'b'] == l2
</syntaxhighlight>
===Extract Elements from the Tail of the List Starting with a Certain Index===
<syntaxhighlight lang='py'>
l = [1, 2, 3]
assert l[0:] == [1, 2, 3]
assert l[1:] == [2, 3]
assert l[2:]== [3]
assert l[3:] == [] # empty list
assert l[4:] == [] # empty list
</syntaxhighlight>
===Extract Elements from the Head of the List Counting from the Tail===
TODO

Revision as of 21:50, 16 May 2024

Internal

Overview

A sub-sequence of a list can be extracted with a slice. The slice [<start-index>:<end-index>:<step>] specified the index of the last element, and the index of the first element not included in slice, and the step. The step is optional, the default value is 1.

l = ['a', 'b', 'c', 'd', 'e', 'f']
assert ['a', 'b', 'c', 'd', 'e', 'f'] == l[:] # starts from the beginning and ends after the end of the list
assert ['c', 'd'] == l[2:4]
assert ['c'] == l[2:4:2]

The step can be negative, which means the slice starts at the end and goes from right to left.

l = ['a', 'b', 'c', 'd', 'e', 'f']
assert ['f', 'e', 'd', 'c', 'b', 'a'] == l[::-1]

[:] creates a copy of the list.

l = ['a', 'b', 'c']
l2 = l[:]
l2[0] = 'x'
assert ['a', 'b', 'c'] == l
assert ['x', 'b', 'c'] == l2

Remove the last element of the list:

l = ['a', 'b', 'c']
l2 = l[:-1]
assert ['a', 'b'] == l2

Extract Elements from the Tail of the List Starting with a Certain Index

l = [1, 2, 3]
assert l[0:] == [1, 2, 3]
assert l[1:] == [2, 3]
assert l[2:]== [3]
assert l[3:] == [] # empty list
assert l[4:] == [] # empty list

Extract Elements from the Head of the List Counting from the Tail

TODO