Monday, April 20, 2015

Basics of the Python Tuple - Python Basics - Python Tutorial

Basics of the Python TupleBasics of the Python Tuple


In this Python Tutorial, we will discuss the basics of the Python tuple which is another data type in the Python programming language. This will be a brief introduction to the tuple and we will cover tuples in full in a later chapter.


What is a Tuple?


A tuple is similar to a list but unlike a list tuples cannot be amended after they have been created which makes them immutable. Tuple is a sequence like a list so we would use the index to call our values.  Tuples are not used all that often in practice but them being immutable give us a little more security which protects them from being changed when the program runs. We normally use tuples for a fixed set of values in our programs. If our values have to be changed in place, then we would be better off using a list over tuple. Python has a few built-in methods that we can call on tuples. We will cover the methods in a future tutorial.


What is the Tuples Syntax?


We indicate to Python that we want to use a tuple by using parentheses( ) and just like list we separate data by commas.


Tuple Syntax 


var = (213, 5643, “Red”, “Blue”)


var1 = (“TV”, “light”, “Camera”, “Seat”)


Some Tuple Examples


Below we will create some tuples and assign them to a variable.  Follow along in your Python interpreter and when you are done with our tuple examples try some on your own.


 


#Create a tuple and assign to a variable.
>>> a = ("Red", "Blue", "White", "Green", "Black", "Orange")

#Call the tuple via the variable
>>> a
('Red', 'Blue', 'White', 'Green', 'Black', 'Orange')

#Create a tuple and assign to a variable.
>>> b = ("123", "456", "789")

#Call the tuple via the variable
>>> b
('123', '456', '789')

#Call a value via the index
>>> b[1]
'456'

#Proof that Tuples are immutable
>>> b[1] = "987"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

Now that you have complete the Python tutorial called Basics of the Python Tuple you learned how to create and call tuples via a variable. We also discussed that tuples are immutable and the are ordered in a sequence.  If you have any questions leave a comment below the basics of the Python tuple.



No comments:

Post a Comment