list – a sequence of objects

Python lists, such as those returned by the string split() method, are sequences of objects. Unlike strings lists are mutable, insofar as the elements within them can be replaced or removed, and new elements can be inserted or appended. lists are the workhorse of Python data structures.

Literal lists are delimited by square brackets, and the items within the list are separated by commas. Here is a list of three numbers:

>>> [1, 9, 8]
[1, 9, 8]

And here is a list of three strings:

>>> a = ["apple", "orange", "pear"]

We can retrieve elements by using square brackets with a zero-based index:

>>> a[1]
"orange"

We can replace elements by assigning to a specific element:

>>> a[1] = 7
>>> a
['apple', 7, 'pear']

See how lists can be heterogeneous with respect to the type of the contained objects. We now have a list containing an str, an int, and another str.

It's often useful to create an empty list, which we can do using empty square brackets:

>>> b = []

We can modify the list in other ways. Let's add some floats to the end of the list using the append() method:

>>> b.append(1.618)
>>> b
[1.618]
>>> b.append(1.414)
[1.618, 1.414]

There are many other useful methods for manipulating lists, which we'll cover in a later chapter. Right now, we just need to be able to perform rudimentary list operations.

There is also a list constructor, which can be used to create lists from other collections, such as strings:

>>> list("characters")
['c', 'h', 'a', 'r', 'a', 'c', 't', 'e', 'r', 's']

Although the significant whitespace rules in Python can, at first, seem very rigid, there is a lot of flexibility. For example, if you have unclosed brackets, braces, or parentheses at the end of a line, you can continue on the next line. This can be very useful for representing long literal collections, or improving the readability of even short collections:

>>> c = ['bear',
... 'giraffe',
... 'elephant',
... 'caterpillar',]
>>> c
['bear', 'giraffe', 'elephant', 'caterpillar']

See also how we're allowed to use an additional comma after the last element, an handy feature that improves the maintainability of the code.

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

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