Python
  Home arrow Python arrow Sequences and Sets in Python
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
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? 
PYTHON

Sequences and Sets in Python
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 1
    2008-10-09

    Table of Contents:
  • Sequences and Sets in Python
  • List methods
  • Set Operations
  • Indexing a Dictionary

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb 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


    Sequences and Sets in Python


    (Page 1 of 4 )

    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.

    Slicing a sequence

    To indicate a subsequence of S , you can use a slicing, with the syntax S[i:j], where i  and j  are integers. S[i:j] is the subsequence of S  from the i th item, included, to the j th item, excluded. In Python, ranges always include the lower bound and exclude the upper bound. A slice is an empty subsequence if j  is less than or equal to i , or if i  is greater than or equal to L , the length of S . You can omit i  if it is equal to 0, so that the slice begins from the start of S. You can omit j  if it is greater than or equal to L, so that the slice extends all the way to the end of S. You can even omit both indices, to mean a copy of the entire sequence: S[:]. Either or both indices may be less than 0. A negative index indicates the same spot inS as L+n , just like in indexing. An index greater than or equal to L  means the end of S, while a negative index less than or equal to -L  means the start of S . Here are some examples:

      x = [1, 2, 3, 4]
      x[1:3]                 # [2, 3]
      x[1:]                  # [2, 3, 4]
      x[:2]                  # [1, 2]

    Slicing can also use the extended syntax S[i:j:k]. k is the stride of the slice, or the distance between successive indices. S[i:j] is equivalent to S[i:j:1], S[::2] is the subsequence of S  that includes all items that have an even index in S , and S[::-1] has the same items as S , but in reverse order.

    Strings

    String objects are immutable, so attempting to rebind or delete an item or slice of a string raises an exception. The items of a string object (corresponding to each of the characters in the string) are themselves strings, each of length 1. The slices of a string object are also strings. String objects have several methods, which are covered in "Methods of String Objects" on page 186.

    Tuples

    Tuple objects are immutable, so attempting to rebind or delete an item or slice of a tuple raises an exception. The items of a tuple are arbitrary objects and may be of different types. The slices of a tuple are also tuples. Tuples have no normal (nonspecial) methods, only some of the special methods covered in "Special Methods" on page 104.

    Lists

    List objects are mutable, so you may rebind or delete items and slices of a list. The items of a list are arbitrary objects and may be of different types. The slices of a list are lists.

    Modifying a list

    You can modify a list by assigning to an indexing. For instance:

      x = [1, 2, 3, 4]
      x[1] = 42              # x is now [1, 42, 3, 4]

    Another way to modify a list object L  is to use a slice of L  as the target (LHS) of an assignment statement. The RHS of the assignment must then be an iterable. If the LHS slice is in extended form, then the RHS must have just as many items as the number of items in the LHS slice. However, if the LHS slice is in normal
    (nonextended) form, then the LHS slice and the RHS may each be of any length; assigning to a (nonextended) slice of a list can add or remove list items. For example:

      x = [1, 2, 3, 4]
      x[1:3] = [22, 33, 44]    # x is now [1, 22, 33, 44, 4]
      x[1:4] = [8, 9]          # x is now [1, 8, 9, 4]

    Here are some important special cases of assignment to slices:

    • Using the empty list [] as the RHS expression removes the target slice from L . In other words, L[i:j]=[] has the same effect as del L[i:j].
    • Using an empty slice of L  as the LHS target inserts the items of the RHS at the appropriate spot in L. In other words, L[i:i]=['a','b'] inserts the items 'a' and 'b' before the item that was at index i  in L  before the assignment.
    • Using a slice that covers the entire list object,
      L[:], as the LHS target totally replaces the contents of L .

    You can delete an item or a slice from a list with del. For instance:

      x = [1, 2, 3, 4, 5]
      del x[1]                 # x is now [1, 3, 4, 5]
      del x[::2]               # x is now [3, 5]

    In-place operations on a list

    List objects define in-place versions of the + and * operators, which you can use via augmented assignment statements. The augmented assignment statement L+=L1  has the effect of adding the items of iterable L1  to the end of L . L*=n  has the effect of adding n-1 copies of L  to the end of L ; if n<=0, L*=n empties the contents of L, like L[:]=[].

    More Python Articles
    More By O'Reilly Media


       · This article is an excerpt from the book "Python in a Nutshell, Second Edition,"...
     

    Buy this book now. This article is excerpted from chapter four of the book Python in a Nutshell, Second Edition, written by Alex Martelli (O'Reilly; ISBN: 0596100469). Check it out today at your favorite bookstore. Buy this book now.

       

    PYTHON ARTICLES

    - 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
    - Mobile Programming in Python using PyS60: UI...
    - Python: Count on It
    - Python Strings: Spinning Yarns
    - Python: More Fun with Strings
    - Python: Stringing You Along

     
    Application Delivery: Everything You Wanted to Know, but Didn`t Know You Needed to Ask
    A comprehensive guide to examining the topics of Wide-area Data Services and app....

     
    Best Practices: Safe and Secure Hardware Asset Recovery
    Companies increasingly must meet EPA and local requirements for the disposal of ....

     
    Managing SSL Security in Multi-Server Environments
    Read this white paper to learn how to simplify management of your organization's....

     
    Open Source Security Myths
    Open Source Software (OSS) is computer software whose source code is available t....

     
    Power and Cooling Capacity Management for Data Centers
    This paper describes the principles for achieving power and cooling capacity man....

     




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway
    Stay green...Green IT