Data structures in python continued.. (tuples) .. [P-4]

Home Forums Python Programming Data structures in python continued.. (tuples) .. [P-4]

Viewing 1 post (of 1 total)
  • Author
    Posts
  • #1942 Reply
    Humble
    Keymaster

    Tuples are represented by () ..

    Code:
    >>> t=1,3,4
    >>> t
    (1, 3, 4)
    >>> type(t)
    <type ‘tuple’>

    If the tuple has only one entry its needed to end it with a “,”.

    Code:
    >>> z=1
    >>> type(z)
    <type ‘int’>
    >>> z=1,
    >>> type(z)
    <type ‘tuple’>
    >>>


    Tuples can be indexed..

    Code:
    >>> t[0]
    1
    >>> t[1]
    3


    Tuples are immutable..

    Code:
    >>> t[1]=5
    Traceback (most recent call last):
    File “<stdin>”, line 1, in <module>
    TypeError: ‘tuple’ object does not support item assignment

    Tuples can be formed with different homogenous data types .. mutables can also be part of tuples..

    Code:
    >>> k = t,2,3,4
    >>> k
    ((1, 3, 4), 2, 3, 4)

    Tuples can be unpacked by having same number of args in left hand side of “=”

    Code:
    >>> k[0]
    (1, 3, 4)
    >>> x,y,z = k[0]
    >>> x
    1
    >>> y
    3
    >>> z
    4

    >>>

    Some methods available for tuples:

    index

    Code:
    >>> k
    ((1, 3, 4), 2, 3, 4, [3, 2, 1])
    >>> k.index(3)
    2
    >>>

    count

    Code:
    >>> k.count(4)
    1
Viewing 1 post (of 1 total)
Reply To: Data structures in python continued.. (tuples) .. [P-4]
Your information: