Slicing Lists

Geneticists describe C. elegans phenotypes (nematodes, a type of microscopic worms) using three-letter short-form markers. Examples include Emb (embryonic lethality), Him (high incidence of males), Unc (uncoordinated), Dpy (dumpy: short and fat), Sma (small), and Lon (long). We can keep a list:

 >>>​​ ​​celegans_phenotypes​​ ​​=​​ ​​[​​'Emb'​​,​​ ​​'Him'​​,​​ ​​'Unc'​​,​​ ​​'Lon'​​,​​ ​​'Dpy'​​,​​ ​​'Sma'​​]
 >>>​​ ​​celegans_phenotypes
 ['Emb', 'Him', 'Unc', 'Lon', 'Dpy', 'Sma']

It turns out that Dpy worms and Sma worms are difficult to distinguish from each other, so they aren’t as easily differentiated in complex strains. We can produce a new list based on celegans_phenotypes but without Dpy or Sma by taking a slice of the list:

 >>>​​ ​​celegans_phenotypes​​ ​​=​​ ​​[​​'Emb'​​,​​ ​​'Him'​​,​​ ​​'Unc'​​,​​ ​​'Lon'​​,​​ ​​'Dpy'​​,​​ ​​'Sma'​​]
 >>>​​ ​​useful_markers​​ ​​=​​ ​​celegans_phenotypes[0:4]

This creates a new list consisting of only the four distinguishable markers, which are the first four items from the list that celegans_phenotypes refers to:

images/lists/slicing.png

The first index in the slice is the starting point. The second index is one more than the index of the last item we want to include. For example, the last item we wanted to include, Lon, had an index of 3, so we use 4 for the second index. More rigorously, list[i:j] is a slice of the original list from index i (inclusive) up to, but not including, index j (exclusive). Python uses this convention to be consistent with the rule that the legal indices for a list go from 0 up to one less than the list’s length.

The first index can be omitted if we want to slice from the beginning of the list, and the last index can be omitted if we want to slice to the end:

 >>>​​ ​​celegans_phenotypes​​ ​​=​​ ​​[​​'Emb'​​,​​ ​​'Him'​​,​​ ​​'Unc'​​,​​ ​​'Lon'​​,​​ ​​'Dpy'​​,​​ ​​'Sma'​​]
 >>>​​ ​​celegans_phenotypes[:4]
 ['Emb', 'Him', 'Unc', 'Lon']
 >>>​​ ​​celegans_phenotypes[4:]
 ['Dpy', 'Sma']

To create a copy of the entire list, omit both indices so that the “slice” runs from the start of the list to its end:

 >>>​​ ​​celegans_phenotypes​​ ​​=​​ ​​[​​'Emb'​​,​​ ​​'Him'​​,​​ ​​'Unc'​​,​​ ​​'Lon'​​,​​ ​​'Dpy'​​,​​ ​​'Sma'​​]
 >>>​​ ​​celegans_copy​​ ​​=​​ ​​celegans_phenotypes[:]
 >>>​​ ​​celegans_phenotypes[5]​​ ​​=​​ ​​'Lvl'
 >>>​​ ​​celegans_phenotypes
 ['Emb', 'Him', 'Unc', 'Lon', 'Dpy', 'Lvl']
 >>>​​ ​​celegans_copy
 ['Emb', 'Him', 'Unc', 'Lon', 'Dpy', 'Sma']

The list referred to by celegans_copy is a clone of the list referred to by celegans_phenotypes. The lists have the same items, but the lists themselves are different objects at different memory addresses:

images/lists/clone.png

In List Methods, you will learn about a list method that can be used to make a copy of a list.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.30.178