Tuple
Hey Shouters!! Today we learn about all the important functions and operations supported by tuples in python.
In this tutorial, we will learn about all the important things about tuples. The main parts that we will learn about are:
Introduction
Creating Tuple
Comprehension and Generator
List and Dictionaries
Operations over tuple
Methods used in the tuple
Tuple and Function
Boolean and tuple
Short Note
Introduction
Tuples are group of values within first brackets i.e. (1,2,3,'str',22.333).
Tuples and Strings are immutable whereas list and dictionaries are mutable.
Tuples are faster than lists.
Tuple can be a dictionary keys but list cannot.
Tuples can be used as values in sets whereas lists can not.
Creating Tuple
No. 1> There are a Tuple class and using tuple class constructor, you can create tuples as well as you can apply conversion like string to tuple, list to tuple and so on.
Tuple allows indexing, slicing operations just like list and String.
Syntax: tuple(iterable)
Here, iterable is a single parameter(optional). Only the iterable types of objects are passed. Does not return anything, but creates a tuple.
What does iterable means?
In simple words, 'iterable' means using a loop, values can be fetched. If 'iterable' is not passed, an empty tuple is created. If 'bool' or 'int' is passed then the "TypeError" message is generated.
Example :
myTuple=tuple(2)
Output:
TypeError: 'int' object is not iterable
No. 2> Using first brackets (), You can declare a tuple.
To create empty tuple use only first brackets but when creating single element tuple then must put a comma(',') after the first value.
Tuples can also be created without parenthesis when more than one value is assigned into a variable.
Example :
myTuple=() # empty tuple
myTuple2=("a") # String
myTuple3=("a",) # tuple
myTuple4="a","b","c" # tuple
COMPREHENSION AND GENERATOR
The word "Comprehension" means "a short and concise way to construct new sequences".
The word "Generator" means "a thing that generates something".
List Comprehension can be made as follows:
Example:
myList = [ i for i in range(6)]
print(myList,end="")
type(myList)
Output:
[0,1,2,3,4,5]
<class 'list'>
Here, we initialize the list using a loop and make a single line compressed statement.
Mainly, List comprehension is enclosed in square brackets [] while the Generator is enclosed in plain parentheses ().
The Generator expression allows us to create a generator without the yield keyword.
Generator expression can be made as follows :
Example:
myGenerator= (n for n in range(10))
for i in myGenerator:
print(i,end=" ") # print using loop
type(myGenerator)
print(myGenerator) # Object location prints
Output:
0 1 2 3 4 5 6 7 8 9
<class 'generator'>
<generator object <genexpr> at 0x00BC73A8>
Note: In a list comprehension, Python reserves memory for the whole list. Whereas, The generator generates one item at a time and generates an item only when in demand. Thus we can say that Generator expressions are memory efficient.
LIST AND DICTIONARIES
Even now we know surprisingly little about Dictionarie's and Tuple's.
Is it possible that tuples and dictionaries can work together?
Answer is Yes, Tuples and dictionaries can work together, although tuples can be used as dictionary keys but lists can never be used as dictionary keys, also tuple containing list is not a valid key. For example :
# No.1: Example (Tuple used as key)
Tuple_Dict = {}
# empty dictionary
Tuple_Dict['0th_key_val'] = "Value"
# assign simple value
Tuple_Dict[('SUB_KEY_1','SUB_KEY_2')] = "Tuple"
# use tuple as key
Tuple_Dict[2]=("3rd","position")
# use tuple as value
#Display
for k in Tuple_Dict:
print("KEY: ", k,"\t VALUE: " ,Tuple_Dict[k])
Output:
KEY: 0th_key_val VALUE: Value
KEY: ('SUB_KEY_1', 'SUB_KEY_2') VALUE: Tuple
KEY: 2 VALUE: ('3rd', 'position')
Be careful about dictionaries, values can be updatable.
# No.2 Example (Tuple used as Values)
cars={}
while True :
company=input("Enter company name (type 'exit' to stop): ")
if company=="exit":
break
model=input("Enter car model: ")
if company in cars:
cars[company] +=(model, )
else:
cars[company] =(model,)
# Display all car companies with models
for company_name in cars.keys():
print("\tCOMPANY: ", company_name, "\nMODELS: ",cars[company_name])
Output:
Enter company name (type 'exit' to stop): Tesla
Enter car model: Model S
Enter company name (type 'exit' to stop): Tesla
Enter car model: Model X
Enter company name (type 'exit' to stop): Tata
Enter car model: Nexon
Enter company name (type 'exit' to stop): Tata
Enter car model: Tiago
Enter company name (type 'exit' to stop): exit
COMPANY: Tesla
MODELS: ('Model S', 'Model X')
COMPANY: Tata
MODELS: ('Nexon', 'Tiago')
Here, 'cars' is my dictionary and 'company' is used as a key in the dictionary and all company manufactured models are stored as a tuple value by inputted as 'model' data. After that Display all car models with company names.
OPERATIONS OVER TUPLE
Tuples can be extended using '+' operator or replicated using '*' operator.
Tuple supports 'in' and 'not in' operations.
A Tuple's elements can be variables, not only literals.
A Tuple's element can be expressions if they're on the right side of the assignment operator.
# Example:
E_tuple= ()
myTuple = ("WATER", "FIRE")
t1 = myTuple + ("LAND", "AIR")
t2 = E_tuple * 3
print(len(E_tuple)) # empty tuple returns '0'.
print("WATER" in myTuple)
print(-10 not in myTuple)
print(t1)
print(t2)
Output:
0
True
True
("WATER", "FIRE", "LAND", "AIR")
()
Here, "t2" is an empty tuple after this "t2 = E_tuple * 3" operation, we get empty tuple.
METHODS USED IN THE TUPLE
COUNT METHOD
Returns the number of times a specified value occurs in a tuple.
INDEX METHOD
Searches the tuple for a specified value and returns the first position of where it was found.
LEN METHOD
The len() function accepts tuples as a parameter and returns the number of elements containing in the tuple.
ENUMERATE METHOD
The enumerate() function returns a tuple containing a count for every iteration (from the start which defaults to 0) and the values obtained from iterating over a sequence.
DEL METHOD
Removing individual tuple elements is not possible. To remove the entire tuple, use the 'del' method. There is no 'pop' method used in the tuple.
# EXAMPLE:
y=True
Tuple = (1,"xyz", 5.73, y, "xyz")
print()
# Access the first item of a tuple at index 0
print(Tuple[0]) # 1
# Update Tuple values
try:
Tuple[1]="ABC"
except:
print("Tuples are immutable")
# Tuples are immutable
# Python supports negative indexing. Negative indexing starts( with -1 ) from the end of the tuple.
print(Tuple[-1]) # xyz
# index method returns first index if found.
print( Tuple.index('xyz')) # 1
# Tuple slicing are used to get new tuple.
print(Tuple[1:3]) # ('xyz',5.73)
# slicing stats at index no 1 and ends at index no 2.
# Iterate through a tuple
for val in (Tuple + ("After","Added", "Values")):
print(val, end=" ")
print()
# 1 xyz 5.73 True xyz After Added Values
# count methods counts a specified value.
print( Tuple.count('xyz')) # 2
# Enumerate function returns a tuple with count value
for i,val in enumerate(Tuple):
print(i, val)
'''
0 1
1 xyz
2 5.73
3 True
4 xyz
'''
# Tuple.extend(44)
# tuple object has no attribute 'extend'.
# Tuple.append(44)
# tuple object has no attribute 'append'.
# Create a new tuple instead of updating
Tuples = Tuple[:]+(2,3,"ABC")
# To delete entire tuple
del(Tuple)
Output :
1
Tuples are immutable
xyz
1
('xyz', 5.73)
1 xyz 5.73 True xyz After Added Values
2
0 1
1 xyz
2 5.73
3 True
4 xyz
Check this program Carefully.
TUPLE AND FUNCTIONS
IS FUNCTION PARAMETER LIST IS A TUPLE?
Answer is No, Function parameter is not a tuple. If function parameters are tuple then, we must use tuple methods or tuple operation over it always, but we can use any kind of operation over function parameters. So, function parameters are not tuples.
Example:
def fun(a):
a=a+5
print(a)
t=(1,2)
fun(t)
output:
TypeError: can only concatenate tuple (not "int") to tuple
You can pass tuple as an argument to a function, in those cases, some operations are restricted.
BOOLEAN AND TUPLE
Why is "True, True, True == (True, True, True)" gives "(True, True, False)"?
Answer: The result "(True, True, False)" is correct.
For equality operator, In left hand side last element is compared with the first element of the right hand side and the second last element on the left hand side is compared with the second element of the right side and so on.
So, For 'True' last element on the left-hand side is compared with '(True, True, True)'. Here, boolean is compared with a tuple, that's why the answer is 'False'. Remaining values ('True','True') are put as it is.
Short Note
A tuple is a collection of dissimilar variables or values.
Tuples can also be used to keep records, such as weather reporters use tuples for recording temperature over an hour/day/month.
**************************************************************
Tuple
Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets.
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate values.
Tuple items are indexed, the first item has index [0]
, the second item has index [1]
etc.
Ordered
When we say that tuples are ordered, it means that the items have a defined order, and that order will not change.
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created.
Allow Duplicates
Since tuples are indexed, they can have items with the same value:
thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)
Tuple Length
To determine how many items a tuple has, use the
len()
function:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
Create Tuple With One Item
To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple.
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Tuple Items - Data Types
Tuple items can be of any data type:
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
A tuple can contain different data types:
A tuple with strings, integers and boolean values:
tuple1 = ("abc", 34, True, 40, "male")
type()
From Python's perspective, tuples are defined as objects with the data type 'tuple':
<class 'tuple'>
mytuple = ("apple", "banana", "cherry")
print(type(mytuple))
The tuple() Constructor
It is also possible to use the tuple() constructor to make a tuple.
Using the tuple() method to make a tuple:
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-bracketsprint(thistuple)
Python Collections (Arrays)
There are four collection data types in the Python programming language:
- List is a collection which is ordered and changeable. Allows duplicate members.
- Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
- Set is a collection which is unordered and unindexed. No duplicate members.
- Dictionary is a collection which is ordered* and changeable. No duplicate members
When choosing a collection type, it is useful to understand the properties of that type. Choosing the right type for a particular data set could mean retention of meaning, and, it could mean an increase in efficiency or security.
******************************************************************
Access Tuple Items
You can access tuple items by referring to the index number, inside square brackets:
Example
Print the second item in the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
Note: The first item has index 0.
Negative Indexing
Negative indexing means start from the end.
-1
refers to the last item,
-2
refers to the second last item etc.
Example
Print the last item of the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new tuple with the specified items.
Example
Return the third, fourth, and fifth item:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")print(thistuple[2:5])
Note: The search will start at index 2 (included) and end at index 5 (not included).
Remember that the first item has index 0.
By leaving out the start value, the range will start at the first item:
Example
This example returns the items from the beginning to, but NOT included, "kiwi":
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")print(thistuple[:4])
By leaving out the end value, the range will go on to the end of the list:
Example
This example returns the items from "cherry" and to the end:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")print(thistuple[2:])
Range of Negative Indexes
Specify negative indexes if you want to start the search from the end of the tuple:
Example
This example returns the items from index -4 (included) to index -1 (excluded)
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[-4:-1])
Check if Item Exists
To determine if a specified item is present in a tuple use the in
keyword:
Example
Check if "apple" is present in the tuple:
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits
tuple")
******************************************************************
Tuples are unchangeable, meaning that you cannot change, add, or remove items once the tuple is created.
But there are some workarounds.
Change Tuple Values
Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.
But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.
Example
Convert the tuple into a list to be able to change it:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x =
tuple(y)
print(x)
Add Items
Since tuples are immutable, they do not have a build-in
append()
method, but
there are other ways to add items to a tuple.
1. Convert into a list: Just like the workaround for changing a tuple, you can convert it into a list, add your item(s), and convert it back into a tuple.
Example
Convert the tuple into a list, add "orange", and convert it back into a tuple:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
thistuple =
tuple(y)
******************************************************************
******************************************************************
******************************************************************
******************************************************************
******************************************************************
EXAMPLE:
1>
mytuple = ("apple", "banana", "cherry","berry", "Guava").
print(mytuple)
('apple', 'banana', 'cherry', 'berry', 'Guava')
2>
print(mytuple[-2])
berry
3>
l1= list(mytuple)
l1.pop(2)
'cherry'
4>
l1.append("orange")
l1.append("pineapple")
5>
l1[-1]="mangoes"
print( l1)
['apple', 'banana', 'berry', 'Guava', 'orange', 'mangoes']
6>
myVeg = tuple(("Potato","Brinjal","Peas","chillies","Tomato","carrot"))
for x in range(len(myVeg)):
l1.append(myVeg[x])
l1
['apple', 'banana', 'berry', 'Guava', 'orange', 'mangoes', 'Potato', 'Brinjal', 'Peas', 'chillies', 'Tomato', 'carrot']
mNT=tuple(l1)
print( mNT)
('apple', 'banana', 'berry', 'Guava', 'orange', 'mangoes', 'Potato', 'Brinjal', 'Peas', 'chillies', 'Tomato', 'carrot')
7>
print(len(mNT))
12
8>
print(mNT.index("berry"))
2
******************************************************************
https://www.guru99.com/python-list-remove-clear-pop-del.html
https://careerkarma.com/blog/python-replace-item-in-list/
Comments
Post a Comment