EP5 Know How to Slice Sequences

  • Avoid being verbose: Don't suply o for the start index or the length of the sequence for the end of index.

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

EP5 Know How to Slice Sequences
I want to know how LINUX works!
EP 15 Know How Closures Interact with Variable Scope
How to use xml.etree.ElementTree
How to use Python-shell
How to know the port number of the xinetd service
How to use tf.data
How to use virtualenv
Scraping 2 How to scrape
How to use Seaboan
How to use image-match
How to use shogun
How to install Python
How to use Pandas 2
How to read PyPI
How to install pip
How to use Virtualenv
How to know the current directory in Python in Blender
How to use numpy.vectorize
How to update easy_install
How to install archlinux
How to use pytest_report_header
How to restart gunicorn
How to install python
How to virtual host
How to debug selenium
How to use partial
How to use Bio.Phylo
How to read JSON
How to use SymPy
How to use x-means
How to use WikiExtractor.py
How to update Spyder
How to use IPython
How to install BayesOpt
How to use virtualenv
How to use Matplotlib
How to use iptables
How to use numpy
How to use TokyoTechFes2015
How to use venv
How to use dictionary {}
How to use Pyenv
How to grow dotfiles
How to use list []
How to use python-kabusapi
How to retrieve multiple arrays using slice in python.
"How to count Fukashigi"
How to install Nbextensions
How to use OptParse
How to use return
How to install Prover9
How to use dotenv
How to operate NumPy
How to use pyenv-virtualenv
How to use Go.mod
How to use imutils
How to use import
How to slice a block multiple array from a multiple array in Python
I didn't know how to use the [python] for statement
How to estimate kernel density