Python - Tuples
Introduction to Tuple.
- Just like list, tuple is also used to store sequence of element.
- Tuple elements can be of any data types.
- Tuple are immutable.
- Tuple are iterable.
- Tuple are ordered built-in data types and unchangeable.
- Tuple is created using the round brackets i.e, () or tuple() constructor.
- Tuple allows duplicate elements.
- Tuple supports indexing.
- Tuple supports slicing.
- 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
- Len() - Returns the total number of elements in a tuple.
- Sum() - Returns the sum of all the elements in a tuple.
- Min() - Returns the minimum elements in a tuple.
- Max() - Returns the maximum elements in a tuple.
Function used to count the number of time specified value appear in a list.
- Count() - Return number of times specified value appear in a list.
Function to know the index of the value in a list.
Q - Write a program to swap two numbers(It using tuple)?
- List is mutable. Tuple is immutable.
- List consume more memory and slow. Tuple consume less memory and fast.
- 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
Post a Comment