Python
  Home arrow Python arrow Page 4 - String and List Python Object Types
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
PYTHON

String and List Python Object Types
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 2
    2009-01-22


    Table of Contents:
  • String and List Python Object Types
  • Immutability
  • Other Ways to Code Strings
  • Lists

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    String and List Python Object Types - Lists
    ( Page 4 of 4 )

     

    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
      3

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

      >>> L[0]                           # Indexing by positio n
     
    12 3

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

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

      >>> L                              # We're not changing the original lis t
     
    [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
      1.23

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

    Here, the list append method expands the list’s size and inserts an item at the end; the pop method (or an equivalent del statement) 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 muta ble, 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 list sort method here, for example, orders the list in ascending fashion by default, and reverse reverses 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 as append instead.

    Nesting

    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
     

       

    PYTHON ARTICLES

    - 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
    - Sequences and Sets in Python
    - Python Expressions and Operators
    - Dictionaries, Variables and Statements in Py...
    - Data Types in Python
    - The Python Language
    - SSH with Twisted





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek