Python - Tuples

 Introduction to Tuple.

  1. Just like list, tuple is also used to store sequence of element.
  2. Tuple elements can be of any data types.
  3. Tuple are immutable.
  4. Tuple are iterable.
  5. Tuple are ordered built-in data types and unchangeable. 
  6. Tuple is created using the round brackets i.e, () or tuple() constructor.
  7. Tuple allows duplicate elements.
  8. Tuple supports indexing.
  9. Tuple supports slicing.
  10. Concatenation and Replication is possible.

Tuple are Unchangeable.

It's means once we have created a tuple using round bracket or  tuple constructor. We can't change , add, or remove item of tuple.

If we try to do that, it's gives error that Tuple object does not support item assignment.

Tuple Methods.

Built-In Function

  1. Len() - Returns the total number of elements in a tuple.
  2. Sum() - Returns the sum of all the elements in a tuple.
  3. Min() - Returns the minimum elements in a tuple.
  4. Max() - Returns the maximum elements in a tuple.

Function used to count the number of time specified value appear in a list.

  1. Count() - Return number of times specified value appear in a list.

Function to know the index of the value in a list.

  1. Index()- Returns the index of first matched item from the tuple. If given element is not in the list generates the value error.

List to tuple.

To convert list into tuple use tuple constructor.





Questions


Q -  Write a program to swap two numbers(It using tuple)?



Q -  Difference between tuple and list?
  1. List is mutable. Tuple is immutable.
  2. List consume more memory and slow. Tuple consume less memory and fast.
  3. When you are returning something from the function the returned value is tuple.
Q -  Why we use tuples?

Tuples are usually used in cases where a statement or a user-defined function can safely assume that the collection of values used will not change.

Q -  What do you mean by Iterable in Python and why tuple is an iterable?
Ans -
Before knowing about iterable you should know about iteration.

Iteration - Repetition of a process.
Iterable -  A python object which supports iteration e.g list, tuple, string, range.

Tuple is an iterable because it's supports sequence of elements. 

Q - Create single element tuple using parenthesis. 

Ans - When you simply create tuple using round bracket for example,  tuple_Variable = (1). And when you check the  type of tuple_Variable is not tuple it's int. So, for creating single value tuple using round bracket used ',' after element.




-- That's all for basic of tuple. It's 5 minute reading.

Comments