***Welcome to ashrafedu.blogspot.com ***This website is maintained by ASHRAF***
***Use tabs for Content***

POSTS

    Tuples

    A tuple is a sequence, very much like a list. The primary difference between tuples and lists is that tuples are immutable. That means that once a tuple is created, it cannot be changed.

    When a tuple is created, enclose its elements in a set of parentheses.

    Example:

    >>> my_tuple = (1, 2, 3, 4, 5)

    >>> print(my_tuple)

    (1, 2, 3, 4, 5)

    Like lists, tuples support indexing, as shown in the following:

    >>> names = ('Ash', 'Amj', 'Anw')

    >>> for i in range(len(names)):

    print(names[i])

    Ash

    Amj

    Anw

    >>> 

    Tuples support all the same operations as lists, except those that change the contents of the list. Tuples support the following:

    • Subscript indexing (for retrieving element values only)

    • Methods such as index

    • Built-in functions such as len, min, and max

    • Slicing expressions

    • The in operator

    • The + and * operators

    Tuples do not support methods such as append, remove, insert, reverse, and sort.

    Why tuple?

    Processing a tuple is faster than processing a list, so tuples are good choices when you are processing lots of data and that data will not be modified. Another reason is that tuples are safe. Because tuples does not allow to change the contents, data can be stored once and rest assured that it will not be modified (accidentally or otherwise) by any code in your program.