Python provides the slice (Slice) operator
L = [' Michael ', ' Sarah ', ' Tracy ', ' Bob ', ' Jack ']
Take first 3 elements
>>> L[0:3]
[' Michael ', ' Sarah ', ' Tracy ']
L[0:3] Indicates that the fetch starts at index 0 until index 3, but does not include index 3. That is, index 0,1,2
you can also start with index 1 and take out 2 elements:
>>> L[1:3]
Python supports l[-1] to take the first element of the countdown, it also supports the inverse slice
>>> l[-2:]
[' Bob ', ' Jack ']
>>> L[-2:-1]
[' Bob ']
Create a sequence of 0-99:
>>> L = list (range)
first 10 numbers, each of two fetch one:
>>> L[:10:2]
[0, 2, 4, 6, 8]
A string can also be seen as a list, with each element being a character. Therefore, strings can also be manipulated with slices
>>> ' ABCDEFG ' [: 3]
' ABC '
>>> ' ABCDEFG ' [:: 2]
' Aceg '
iteration
By default, the Dict iteration is key. If you want to iterate over value, you can use for value in D.values (), if you want to iterate both key and value at the same time, you can use for K, V in D.items ()
>>> d = {' A ': 1, ' B ': 2, ' C ': 3}
>>> for key in D:
... Print (key)
...
a
c
b
>>> for ch in ' ABC ':
... print (CH)
...
a
b
c
python the built-in enumerate function can turn a list into an index-element pair, This allows you to iterate both the index and the element itself in the FOR loop:
>>> for I, value in enumerate ([' A ', ' B ', ' C '):
...
0 A
1 B
2 C
>>> from collections Import iterable
>>> isinstance (' abc ', iterable) # whether STR can iterate
True
Any iterator object can be used for a for loop, including our custom data types, and can be used for loops as long as the iteration criteria are met.
Python Slicing & iterating