Tuesday 21 July 2015

Concept of Tuples in python !

So far, you have seen two compound types: strings, which are made up of characters; and lists, which are made up of elements of any type.There is another type in Python called a tuple that is similar to a list except that it is immutable. A tuple is generally applied when the number of elements is fixed by the nature of the problem.
We'll look at tuples from a number of viewpoints: operations, built-in functions and methods.

Defining a tuple :
>>>portList = ("21", "80", "443", "25")
>>> portList
('21', '80', '443', '25')
>>>


             
      

A tuple is defined in the same way as a list, except that the whole set of elements is enclosed in parentheses instead of square brackets.

The major difference between tuples and lists is that tuples can not be changed. In technical terms, tuples are immutable. They have no methods that would allow you to change them. Lists have methods like append(), extend(), insert(), remove(), and pop(). Tuples have none of these methods.

Tuple Operations :
There are three standard sequence operations (‘+’, ‘*’, ‘[]’) that can be performed with tuples as well as
other sequences.
The ‘+’ operator creates a new tuple as the concatenation of the arguments

>>> ("Hello",World) + ("This","is","tuples")
('Hello',World, 'This', 'is', 'tuples')


Tuple Built-in Functions :
The tuple() function creates a tuple out of another sequence object.
1.  len(): For tuples, this function returns the number of items.

2. max(): For tuples, this function returns the maximum item.

3. min(): For tuples, this function returns the minimum item.

4. sum(): For tuples, this function sums the individual items.

If you like this post or have any question, please feel free to comment!

No comments:

Post a Comment

Blogger Widget