Python
  Home arrow Python arrow Page 2 - Data Structures in Python: Lists and Tuples
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

Data Structures in Python: Lists and Tuples
By: A.P.Rajshekhar
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 11
    2007-01-29


    Table of Contents:
  • Data Structures in Python: Lists and Tuples
  • List
  • Tuple
  • Lists and Tuples in the Real World

  • 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


    Data Structures in Python: Lists and Tuples - List
    ( Page 2 of 4 )



    By definition a list is "An instance of an abstract data type (ADT), formalizing the concept of an ordered collection of entities." In other words, a list is a collection of objects. In contrast with an array, a list contains different objects. That's how Python also views lists. Data types (that's what Python calls built-in data structures too) such as list are known as compound data types in Python. The operations that can be performed on a list are:

    1. Creation
    2. Addition of elements
    3. Accessing and searching
    4. Deletion

    Many of the library functions essentially create lists. These functions may be working on lists themselves during such tasks as accessing and searching. Here are the details:

    Creation: A list is defined as a list of comma-separated values between square brackets thus:

    a = ['spam', 'eggs', 100, 1234]

    where the items of the List a are of different data types. This is the most common method of creating a list. The other technique is to use the range() function. The range() function provides a list of consecutive integers. The range() function takes two arguments. The list returned contains all the integers from the first to the second, including the first but not including the second. For example,

    >>range(1, 5)

    Gives

    [1,2,3,4]

    Since a list itself is a data type, a list can contain another list. For example,

    [1,"a",[2,3]]

    is a perfectly valid list.

    Addition of elements: There are three ways to add elements to an existing List using member functions of the list. These are:

    1. Append, which adds a single element to the end of the list. For example, let li be a List, then

      >>> li
      ['a', 'b', 'mpilgrim', 'z', 'example']
      >>> li.append("new")
      >>> li
      ['a', 'b', 'mpilgrim', 'z', 'example', 'new']
    2. Insert is a method that inserts a single element into the list. The numeric argument is the index of the first element that gets shifted out of position. Also there can be two elements of the same value at two different positions.

      >>> li.insert(2, "new")
      >>> li
      ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new']
    3. Extend concatenates the list passed as argument with the existing list.
      For example:

      >>> li.extend(["two", "elements"])
      >>> li
      ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']

    Accessing and Searching: For accessing and searching, one of the following techniques can be used:

    1. Slicing: A slice is a sub-list of a list. Slicing is done using the [n : m] which returns the part of the list from the nth character to the m-nth character, including the first but excluding the last. For example, if a_list is a list of letters of the alphabet from a to f, then

      >>> a_list = ['a', 'b', 'c', 'd', 'e', 'f']
      >>> a_list[1:3]
      ['b', 'c']
      >>> a_list[:4]
      ['a', 'b', 'c', 'd']
      >>> a_list[3:]
      ['d', 'e', 'f']
      >>> a_list[:]
      ['a', 'b', 'c', 'd', 'e', 'f']
    2. Indexing: An index of a given element can be found using the index() function of list. It returns the first occurrence of the element supplied as an argument. That means even if the element occurs twice, only the position of the first element would be returned. If the element is not found an exception is raised. For example:

      >>>li=['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
      >>> li
      ['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
      >>> li.index("example")
      5
      >>> li.index("new")
      2
      >>> li.index("c")
      Traceback (innermost last):
      File "<interactive input>", line 1, in ?
      ValueError: list.index(x): x not in list

    Apart from these, a list can be accessed as one would access an array by specifying the index thus:

    >>>li=['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
    >>>li[0]
    'a'

    Deletion: To delete an element from a list, one can use del. It removes an element from the specified list. For example:

    >>> a = ['one', 'two', 'three']
    >>> del a[1]
    >>> a
    ['one', 'three']

    del also can have slice thus:
    >>> a_list = ['a', 'b', 'c', 'd', 'e', 'f']
    >>> del a_list[1:5]
    >>> print a_list
    ['a', 'f']

    That covers the operations on lists. The way the operations are implemented shows the flexibility of Python's middle path approach. The flexibility doesn't just stop here. Though strings are immutable and lists are mutable, strings and lists can be converted into each other. 

    Two of the most useful functions in the string module involve lists of strings: split and join. The former returns a list composed of individual elements of string separated by the delimiter passed as an argument. The latter creates a string out of a supplied list. Take a look at the following examples:

    >>> import string
    >>> song = "The rain in Spain..."
    >>> string.split(song)
    ['The', 'rain', 'in', 'Spain...']

    Here the string is split on the basis of space as a delimiter, which is the default delimiter. The next example shows the reverse of the above functionality, a string from a list:

    >>> lst = ['The', 'rain', 'in', 'Spain...']
    >>> string.join(lst)
    'The rain in Spain...'

    The joining is done on the basis of a space delimiter, which again is the default delimiter. We're finished with lists for the moment. Now let's look at the other compound data type, the tuple.



     
     
    >>> More Python Articles          >>> More By A.P.Rajshekhar
     

       

    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 5 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek