Home arrow Python arrow Page 2 - Data Structures in Python: Lists and Tuples

List - Python

Different languages use different kinds of data structures to handle the way data is arranged in memory. This article looks at two of the more common data structures used by Python.

TABLE OF CONTENTS:
  1. Data Structures in Python: Lists and Tuples
  2. List
  3. Tuple
  4. Lists and Tuples in the Real World
By: A.P.Rajshekhar
Rating: starstarstarstarstar / 14
January 29, 2007

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement


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
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PYTHON ARTICLES

- 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: