Home arrow Python arrow Page 4 - String and List Python Object Types

Lists - Python

Last week, we introduced you to the different Python object types, starting with numbers. This week, we'll cover strings and begin our discussion of lists. This article, the second in a four-part series, is excerpted from chapter four of the book Learning Python, Third Edition, written by Mark Lutz (O'Reilly, 2008; ISBN: 0596513984). Copyright © 2008 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

  1. String and List Python Object Types
  2. Immutability
  3. Other Ways to Code Strings
  4. Lists
By: O'Reilly Media
Rating: starstarstarstarstar / 4
January 22, 2009

print this article



The Python list object is the most general sequence provided by the language. Lists are positionally ordered collections of arbitrarily typed objects, and they have no fixed size. They are also mutable—unlike strings, lists can be modified in-place by assignment to offsets as well as a variety of list method calls.

Sequence Operations

Because they are sequences, lists support all the sequence operations we discussed for strings; the only difference is that results are usually lists instead of strings. For instance, given a three-item list:

  >>> L = [123, 'spam', 1.23]          # A list of three different-type objects
>>> len(L)                             # Number of items in the list

we can index, slice, and so on, just as for strings:

  >>> L[0]                           # Indexing by position

  >>> L[:-1]                         # Slicing a list returns a new list
[123, 'spam']

  >>> L + [4, 5, 6]                  # Concatenation makes a new list too
[123, 'spam', 1.23, 4, 5, 6]

  >>> L                              # We're not changing the original list
[123, 'spam', 1.23]

Type-Specific Operations

Python’s lists are related to arrays in other languages, but they tend to be more powerful. For one thing, they have no fixed type constraint—the list we just looked at, for example, contains three objects of completely different types (an integer, a string, and a floating-point number). Further, lists have no fixed size. That is, they can grow and shrink on demand, in response to list-specific operations:

  >>> L.append('NI')                 # Growing: add object at end of list
>>> L
  [123, 'spam', 1.23, 'NI']

  >>> L.pop(2)                       # Shrinking: delete an item in the middle

  >>> L                                  # "del L[2]" deletes from a list too
  [123, 'spam', 'NI']

Here, the listappend method expands the list’s size and inserts an item at the end; thepopmethod (or an equivalentdelstatement) then removes an item at a given offset, causing the list to shrink. Other list methods insert items at an arbitrary position (insert), remove a given item by value (remove), and so on. Because lists are mutable, most list methods also change the list object in-place, instead of creating a new one:

  >>> M = ['bb', 'aa', 'cc']
  >>> M.sort()
>>> M
  ['aa', 'bb', 'cc']

  >>> M.reverse()
  >>> M
  ['cc', 'bb', 'aa']

The listsortmethod here, for example, orders the list in ascending fashion by default, andreversereverses it—in both cases, the methods modify the list directly.

Bounds Checking

Although lists have no fixed size, Python still doesn’t allow us to reference items that are not present. Indexing off the end of a list is always a mistake, but so is assigning off the end:

  >>> L
  [123, 'spam', 'NI']

  >>> L[99]

  ...error text omitted...
IndexError: list index out of range

  >>> L[99] = 1
...error text omitted...
IndexError: list assignment index out of range

This is on purpose, as it’s usually an error to try to assign off the end of a list (and a particularly nasty one in the C language, which doesn’t do as much error checking as Python). Rather than silently growing the list in response, Python reports an error. To grow a list, we call list methods such asappendinstead.


One nice feature of Python’s core data types is that they support arbitrary nesting—we can nest them in any combination, and as deeply as we like (for example, we can have a list that contains a dictionary, which contains another list, and so on). One immediate application of this feature is to represent matrixes, or “multidimensional arrays” in Python. A list with nested lists will do the job for basic applications:

  >>> M = [[1, 2, 3],         # A 3 x 3 matrix, as nested lists 
[4, 5, 6],
[7, 8, 9]]
>>> M
  [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Here, we’ve coded a list that contains three other lists. The effect is to represent a 3× 3 matrix of numbers. Such a structure can be accessed in a variety of ways:

  >>> M[1]                 # Get row 2 
  [4, 5, 6]

  >>> M[1][2]              # Get row 2, then get item 3 within the row

The first operation here fetches the entire second row, and the second grabs the third item within that row—stringing together index operations takes us deeper and deeper into our nested-object structure.*

Please check back next week for the continuation of this article.

>>> More Python Articles          >>> More By O'Reilly Media

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Python Big Data Company Gets DARPA Funding
- Python 32 Now Available
- Final Alpha for Python 3.2 is Released
- Python 3.1: String Formatting
- Python 3.1: Strings and Quotes
- Python 3.1: Programming Basics and Strings
- Tuples and Other Python Object Types
- The Dictionary Python Object Type
- String and List Python Object Types
- Introducing Python Object Types
- Mobile Programming using PyS60: Advanced UI ...
- Nested Functions in Python
- Python Parameters, Functions and Arguments
- Python Statements and Functions
- Statements and Iterators in Python

Developer Shed Affiliates


Dev Shed Tutorial Topics: