Python Tuples (JNNC Technologies)



Tuples are immutable lists and cannot be change in anyway once it is created.
Some of the characteristics features of Tuples are:
  • Tuples are defined in the same way as lists
  • They are enclosed within parenthesis and not within square braces
  • Elements of the tuple must have a defined order
  • Negative indices are counted from the end of the tuple, just like lists
Tuple also have the same structure where the values are separated by commas.
An example showing how to build tuples in Python:
Example:
#!/usr/bin/python

    tupl1 = ('computersc', 'IT', 'CSE');
    tup2 = (6,5,4,3,2,1);

Accessing Values In Tuples

Programs to show how to access values in Tuples:
Example:
#!/usr/bin/python

    Programs to show how to access values in Tuples:
    tupl1 = ('computersc', 'IT', 'CSE');
    tupl2 = (1993, 2016);
    tupl3 = (2, 4, 6, 8, 10, 12, 14, 16);
    print "tupl1[0]", tupl1[0]
    print "tupl3[2:4]", tupl3[2:4]

Updating Tuples

They are immutable i.e. the values can’t be changed directly. So we can just update by joining tuples. Let’s demonstrate this with an example:
Example:
#!/usr/bin/python

    tupl1 = (2, 3, 4);
    tupl2 = ('ab', 'cd');
    tupl3 = tupl1 + tupl2
    print tupl3
This code snippet will execute a combination of two tuples using the “+” operator.
(2, 3, 4, 'ab', 'cd')

Delete Elements From Tuples

To delete a tuple, we can use the del-statement. The syntax for deleting the tuple is:
Syntax:
#!/usr/bin/python

del tuple_name;
Example:

#!/usr/bin/python

tupl3 = (2, 4, 6, 8, 10, 12, 14, 16);

del tupl3;

Post a Comment

0 Comments

'; (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })();