Lists




(chp09_01)




(chp09_01a)




(chp09_02)




(chp09_4)




(chp09_5)




(chp09_6)

Lists are Mutable

  • Unlike strings, lists are mutable.
  • This means we can change an item in a list by accessing it directly as part of the assignment statement.
  • Using the indexing operator (square brackets) on the left side of an assignment, we can update one of the list items.



(ch09_7)

List Deletion

  • Using slices to delete list elements can be awkward and therefore error-prone.
  • The del statement removes an element from a list by using its position.



(ch09_11)

As you might expect, del handles negative indices and causes a runtime error if the index is out of range.

Nested Lists

  • A nested list is a list that appears as an element in another list.
  • To extract an element from the nested list, we can proceed in two steps.
  • First, extract the nested list, then extract the item of interest.
  • It is also possible to combine those steps using bracket operators that evaluate from left to right.



(chp09_nest)

Split and Join

The split method breaks a string into a list of words. By default, any number of whitespace characters is considered a word boundary.




(ch09_split1)

An optional argument called a delimiter can be used to specify which characters to use as word boundaries. The following example uses the string ai as the delimiter:




(ch09_split2)

Notice that the delimiter doesn’t appear in the result.

The inverse of the split method is join. You choose a desired separator string, (often called the glue) and join the list with the glue between each of the elements.




(ch09_join)

The list that you glue together (wds in this example) is not modified. Also, you can use empty glue or multi-character strings as glue.

list Type Conversion Function

Python has a built-in type conversion function called list that tries to turn whatever you give it into a list. For example, try the following:




(ch09_list1)

Lists and for loops

It is also possible to perform list traversal using iteration by item as well as iteration by index.




(chp09_03a)

We can also use the indices to access the items in an iterative fashion.




(chp09_03b)

Next Section - Objects and References