Home arrow Python arrow Page 2 - Sequences and Sets in Python

List methods - Python

In this fifth part of a nine-part series on the Python language, you'll learn about sequences, lists, sets, and more. This article is excerpted from chapter four of the book Python in a Nutshell, Second Edition, written by Alex Martelli (O'Reilly; ISBN: 0596100469). Copyright 2007 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

TABLE OF CONTENTS:
  1. Sequences and Sets in Python
  2. List methods
  3. Set Operations
  4. Indexing a Dictionary
By: O'Reilly Media
Rating: starstarstarstarstar / 3
October 09, 2008

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

List objects provide several methods, as shown in Table 4-3. Nonmutating methods return a result without altering the object to which they apply, while mutating methods may alter the object to which they apply. Many of the mutating methods behave like assignments to appropriate slices of the list. In Table 4-3, L  indicates any list object, i any valid index in L , s  any iterable, and x  any object.

Table 4-3. List object methods

Method

Description

Nonmutating methods

 

L.count(x)

Returns the number of items of Lthat are equal to x.

L.index(x)

Returns the index of the first occurrence of an item in Lthat is equal to x, or raises an exception if Lhas no such item.

Mutating methods

 

L.append(x)

Appends item xto the end of L; e.g., L[len(L):]=[x].

L.extend(s)

Appends all the items of iterable sto the end of L; e.g., L[len(L):]=s.

L.insert(i, x)

Inserts item xin Lbefore the item at index i, moving following items of L(if any) "rightward" to make space (increases len(L) by one, does not replace any item, does not raise exceptions: acts just like L[i:i]=[x]).

L.remove(x)

Removes from L the first occurrence of an item in L that is equal to x, or raises an exception if Lhas no such item.

L.pop([i])

Returns the value of the item at index iand removes it from L; if iis omitted, removes and returns the last item; raises an exception if Lis empty or iis an invalid index in L.

L.reverse()

Reverses, in place, the items of L.

L.sort([f])(2.3)

Sorts, in place, the items of L, comparing items pairwise via function f; if fis omitted, comparison is via the built-in function cmp. For more details, see "Sorting a list" on page 57.

L.sort(cmp=cmp, key=None, reverse=False)(2.4)

Sorts, in-place, the items of L, comparing items pairwise via the function passed as cmp (by default, the built-in function cmp). When argument key is not None, what gets compared for each item x is key(x), not x itself. For more details, see "Sorting a list" on page 57.

All mutating methods of list objects, except pop , return None .

Sorting a list

A list's method sort causes the list to be sorted in-place (its items are reordered to place them in increasing order) in a way that is guaranteed to be stable (elements that compare equal are not exchanged). In practice, sort is extremely fast, often preternaturally fast, as it can exploit any order or reverse order that may be present in any sublist (the advanced algorithm sort uses, known as timsort to honor its developer, Tim Peters, is technically a "non-recursive adaptive stable natural mergesort/binary insertion sort hybrid").

In Python 2.3, a lists sort method takes one optional argument. If present, the argument must be a function that, when called with any two list items as
arguments, returns -1, 0, or 1, depending on whether the first item is to be considered less than, equal to, or greater than the second item for sorting purposes. Passing the argument slows down the sort, although it makes it easy to sort small lists in flexible ways. The decorate-sort-undecorate idiom, covered in "Searching and sorting" on page 485 is faster, at least as flexible, and often less error-prone than passing an argument to sort.

In Python 2.4, the sort method takes three optional arguments, which may be passed with either positional or named-argument syntax. Argument cmp  plays just the same role as the only (unnamed) optional argument in Python 2.3. Argument key , if not None, must be a function that can be called with any list item as its only argument. In this case, to compare any two items x  and y , Python uses cmp(key(x),key(y)) rather than cmp(x,y) (in practice, this is implemented in the same way as the decorate-sort-undecorate idiom presented in "Searching and sorting" on page 485, and can be even faster). Argument reverse , if True, causes the result of each comparison to be reversed; this is not the same thing as reversing L  after sorting because the sort is stable (elements that compare equal are never exchanged) whether argument reverse  is true or false.

Python 2.4 also provides a new built-in function sorted (covered in sorted on page 167) to produce a sorted list from any input iterable. sorted accepts the same input arguments as a lists method sort. Moreover, Python 2.4 adds to module operator (covered in "The operator Module" on page 368) two new higher-order functions, attrgetter and itemgetter, which produce functions particularly suitable for the key= optional argument of lists' method sort and the new built-in function sorted. In Python 2.5, an identical key=  optional argument has also been added to built-in functions min and max, and to functions nsmallest and nlargest in standard library module heapq, covered in "The heapq Module" on page 177.



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

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: