- Avoid being verbose: Don't suply o for the start index or the length of the sequence for the end of index.
a[:30]
or a[-2o:]
)Effective Python
In [9]: a = "a b c d e f g h".split()
In [10]:
In [10]: first_twenty_items = a[:20]
In [11]: first_twenty_items = a[-20:]
In [12]:
In [12]: a[20]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-12-f8db3c71230c> in <module>()
----> 1 a[20]
IndexError: list index out of range
asigning slice of list does not affect to the origin of slice.
In [3]: a = "a b c d e f g h".split()
In [4]: b = a[4:]
In [5]: print('Before' , b)
Before ['e', 'f', 'g', 'h']
In [6]: b[1] = 99
In [7]: print('After', b)
After ['e', 99, 'g', 'h']
In [8]: print('No change', a)
No change ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
assigin some list to slice affects to the origin of slice
In [25]: a = "a b c d e f g h".split()
In [26]: b = a
In [27]: print('Before', a)
Before ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
In [28]: a[:] = [100, 101, 102]
In [29]: assert a is b
In [30]: print('After', a)
After [100, 101, 102]
Recommended Posts