Tuples

walden systems, geeks corner, programming, languages, python, tuples, lists, string
Python is a programming language that lets you work quickly and integrate systems more effectively.

A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets. Creating a tuple is as simple as putting different comma-separated values. Optionally you can put these comma-separated values between parentheses also. To write a tuple containing a single value you have to include a comma, even though there is only one value. The empty tuple is written as two parentheses containing nothing. Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.

Below are some examples on creating tuples

    tup1 = ('apple, 'orange', 'banana', 'strawberry'); 
    tup2 = (1, 2, 3, 4, 5 ); 
    tup3 = "a", "b", "c", "d"; 

    Single tuple 
    tup1 = (50,); 

    Empty tuple 
    tup1 = ();


Updating Tuples

Tuples are immutable which means you cannot update or change the values of tuple elements. You are able to take portions of existing tuples to create new tuples. Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded. To explicitly remove an entire tuple, just use the del statement.

Adding tuples

    tup1 = ('apple', 'banana'); 
    tup2 = ('orange', 'pear'); 
    tup3 = tup1 + tup2; 


Deleting tuple
    tup1 = ('apple, 'orange', 'banana', 'strawberry'); 
    del tup1;

Tuples Operations

Tuples respond to the + and * operators much like strings. The "+" means concatenate and "*" means repetition. Unlike strings, the operation results in a new tuple. Because tuples are sequences, indexing and slicing work the same as for strings.

Below are some basic tuple operations and their results.

Length

 
    len((1, 2, 3)) ; 
    # returns 3 


Concatenation
 
    (1, 2, 3) + (4, 5, 6) ; 
    # New tuple is (1, 2, 3, 4, 5, 6) 


Repetition
    ('Hello',) * 2 ; 
    # New tuple is ('Hello','Hello') 


Membership
 
    3 in (1, 2, 3) ; 
    # Results true since 3 is in the tuple 


Iteration
    for x in (1, 2, 3): 
        print x ; 
    # prints 1 2 3 


Indexing
 
    tup1 = ('apple, 'orange', 'banana', 'strawberry'); 
    tuple[2] 
    # results in orange 
    tuple[-2] 
    # results in banana 
    tuple[3:] 
    # results in ('banana', 'strawberry' )

Tuple Functions

Python has the following tuple functions:

compare elements of tuple1 and tuple2
cmp(tuple1, tuple2)

Gives the total length of the tuple
len(tuple)

Returns item from the tuple with max value
max(tuple)

Returns item from the tuple with min value
min(tuple)