[go: up one dir, main page]

0% found this document useful (0 votes)
8 views33 pages

Python Dictionary and Tuple - Module3

Python notes bca 5th semester

Uploaded by

Akku
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views33 pages

Python Dictionary and Tuple - Module3

Python notes bca 5th semester

Uploaded by

Akku
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Python Dictionary

Dictionaries are a useful data structure for storing data in Python because they are
capable of imitating real-world data arrangements where a certain value exists for a given
key.

The data is stored as key-value pairs using a Python dictionary.

○ This data structure is mutable

○ The components of the dictionary were made using keys and values.

○ Keys must only have one component.

○ Values can be of any type, including integer, list, and tuple.

A dictionary is, in other words, a group of key-value pairs, where the values can be any
Python object. The keys, in contrast, are immutable Python objects, such as strings,
tuples, or numbers. Dictionary entries are ordered as of Python version 3.7. In Python 3.6
and before, dictionaries are generally unordered.

Creating the Dictionary

Curly brackets are the simplest way to generate a Python dictionary, although there are
other approaches as well. With many key-value pairs surrounded in curly brackets and a
colon separating each key from its value, the dictionary can be built. (:). The following
provides the syntax for defining the dictionary.

Syntax:

1. Dict = {"Name": "Gayle", "Age": 25}

In the above dictionary Dict, The keys Name and Age are the strings which come under
the category of an immutable object.

Let's see an example to create a dictionary and print its content.

Code

1. Employee = {"Name": "Johnny", "Age": 32, "salary":26000,"Company":"^TCS"}


2. print(type(Employee))
3. print("printing Employee data .... ")
4. print(Employee)

Output

<class 'dict'>
printing Employee data ....
{'Name': 'Johnny', 'Age': 32, 'salary': 26000, 'Company': TCS}

Python provides the built-in function dict() method which is also used to create the
dictionary.

The empty curly braces {} is used to create empty dictionary.

Code

1. # Creating an empty Dictionary


2. Dict = {}
3. print("Empty Dictionary: ")
4. print(Dict)
5.
6. # Creating a Dictionary
7. # with dict() method
8. Dict = dict({1: 'Hcl', 2: 'WIPRO', 3:'Facebook'})
9. print("\nCreate Dictionary by using dict(): ")
10. print(Dict)
11.
12. # Creating a Dictionary
13. # with each item as a Pair
14. Dict = dict([(4, 'Rinku'), (2, Singh)])
15. print("\nDictionary with each item as a pair: ")
16. print(Dict)

Output

Empty Dictionary:
{}

Create Dictionary by using dict():


{1: 'Hcl', 2: 'WIPRO', 3: 'Facebook'}

Dictionary with each item as a pair:


{4: 'Rinku', 2: 'Singh'}

Accessing the dictionary values

To access data contained in lists and tuples, indexing has been studied. The keys of the
dictionary can be used to obtain the values because they are unique from one another. The
following method can be used to access dictionary values.

Code

1. Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}


2. print(type(Employee))
3. print("printing Employee data .... ")
4. print("Name : %s" %Employee["Name"])
5. print("Age : %d" %Employee["Age"])
6. print("Salary : %d" %Employee["salary"])
7. print("Company : %s" %Employee["Company"])

Output

ee["Company"])
Output
<class 'dict'>
printing Employee data ....
Name : Dev
Age : 20
Salary : 45000
Company : WIPRO

Python provides us with an alternative to use the get() method to access the dictionary
values. It would give the same result as given by the indexing.

Adding Dictionary Values

The dictionary is a mutable data type, and utilising the right keys allows you to change its
values. Dict[key] = value and the value can both be modified. An existing value can also
be updated using the update() method.

Note: The value is updated if the key-value pair is already present in the dictionary.
Otherwise, the dictionary's newly added keys.

Let's see an example to update the dictionary values.

Example - 1:

Code

1. # Creating an empty Dictionary


2. Dict = {}
3. print("Empty Dictionary: ")
4. print(Dict)
5.
6. # Adding elements to dictionary one at a time
7. Dict[0] = 'Peter'
8. Dict[2] = 'Joseph'
9. Dict[3] = 'Ricky'
10. print("\nDictionary after adding 3 elements: ")
11. print(Dict)
12.
13. # Adding set of values
14. # with a single Key
15. # The Emp_ages doesn't exist to dictionary
16. Dict['Emp_ages'] = 20, 33, 24
17. print("\nDictionary after adding 3 elements: ")
18. print(Dict)
19.
20. # Updating existing Key's Value
21. Dict[3] = 'JavaTpoint'
22. print("\nUpdated key value: ")
23. print(Dict)

Output

Empty Dictionary:
{}

Dictionary after adding 3 elements:


{0: 'Peter', 2: 'Joseph', 3: 'Ricky'}

Dictionary after adding 3 elements:


{0: 'Peter', 2: 'Joseph', 3: 'Ricky', 'Emp_ages': (20, 33, 24)}

Updated key value:


{0: 'Peter', 2: 'Joseph', 3: 'JavaTpoint', 'Emp_ages': (20, 33, 24)}

Example - 2:
Code

1. Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}


2. print(type(Employee))
3. print("printing Employee data .... ")
4. print(Employee)
5. print("Enter the details of the new employee....");
6. Employee["Name"] = input("Name: ");
7. Employee["Age"] = int(input("Age: "));
8. Employee["salary"] = int(input("Salary: "));
9. Employee["Company"] = input("Company:");
10. print("printing the new data");
11. print(Employee)

Output

<class 'dict'>
printing Employee data ....
Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"} Enter
the details of the new employee....
Name: Sunny
Age: 38
Salary: 39000
Company:Hcl
printing the new data
{'Name': 'Sunny', 'Age': 38, 'salary': 39000, 'Company': 'Hcl'}

Deleting Elements using del Keyword

The items of the dictionary can be deleted by using the del keyword as given below.

Code
1. Employee = {"Name": "David", "Age": 30,
"salary":55000,"Company":"WIPRO"}
2. print(type(Employee))
3. print("printing Employee data .... ")
4. print(Employee)
5. print("Deleting some of the employee data")
6. del Employee["Name"]
7. del Employee["Company"]
8. print("printing the modified information ")
9. print(Employee)
10. print("Deleting the dictionary: Employee");
11. del Employee
12. print("Lets try to print it again ");
13. print(Employee)

Output

<class 'dict'>
printing Employee data ....
{'Name': 'David', 'Age': 30, 'salary': 55000, 'Company': 'WIPRO'}
Deleting some of the employee data
printing the modified information
{'Age': 30, 'salary': 55000}
Deleting the dictionary: Employee
Lets try to print it again
NameError: name 'Employee' is not defined.

The last print statement in the above code, it raised an error because we tried to print the
Employee dictionary that already deleted.

Deleting Elements using pop() Method


A dictionary is a group of key-value pairs in Python. You can retrieve, insert, and remove
items using this unordered, mutable data type by using their keys. The pop() method is
one of the ways to get rid of elements from a dictionary. In this post, we'll talk about how
to remove items from a Python dictionary using the pop() method.

The value connected to a specific key in a dictionary is removed using the pop() method,
which then returns the value. The key of the element to be removed is the only argument
needed. The pop() method can be used in the following ways:

Code

1. # Creating a Dictionary
2. Dict1 = {1: 'JavaTpoint', 2: 'Educational', 3: 'Website'}
3. # Deleting a key
4. # using pop() method
5. pop_key = Dict1.pop(2)
6. print(Dict1)

Output

{1: 'JavaTpoint', 3: 'Website'}

Additionally, Python offers built-in functions popitem() and clear() for removing
dictionary items. In contrast to the clear() method, which removes all of the elements
from the entire dictionary, popitem() removes any element from a dictionary.

Iterating Dictionary

A dictionary can be iterated using for loop as given below.

Example 1

Code

1. # for loop to print all the keys of a dictionary


2. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
3. for x in Employee:
4. print(x)

Output

Name
Age
salary
Company

Example 2

Code

1. #for loop to print all the values of the dictionary


2. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
for x in Employee:
3. print(Employee[x])

Output

John
29
25000
WIPRO

Example - 3

Code

1. #for loop to print the values of the dictionary by using values() method.
2. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
3. for x in Employee.values():
4. print(x)
Output

John
29
25000
WIPRO

Example 4

Code

1. #for loop to print the items of the dictionary by using items() method
2. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"WIPRO"}
3. for x in Employee.items():
4. print(x)

Output

('Name', 'John')
('Age', 29)
('salary', 25000)
('Company', 'WIPRO')

Properties of Dictionary Keys

1. In the dictionary, we cannot store multiple values for the same keys. If we pass more
than one value for a single key, then the value which is last assigned is considered as the
value of the key.

Consider the following example.

Code

1. Employee={"Name":"John","Age":29,"Salary":25000,"Company":"WIPRO","Na
me":
2. "John"}
3. for x,y in Employee.items():
4. print(x,y)

Output

Name John
Age 29
Salary 25000
Company WIPRO

2. The key cannot belong to any mutable object in Python. Numbers, strings, or tuples
can be used as the key, however mutable objects like lists cannot be used as the key in a
dictionary.

Consider the following example.

Code

1. Employee = {"Name": "John", "Age": 29,


"salary":26000,"Company":"WIPRO",[100,201,301]:"Department ID"}
2. for x,y in Employee.items():
3. print(x,y)

Output

Traceback (most recent call last):


File "dictionary.py", line 1, in
Employee = {"Name": "John", "Age": 29,
"salary":26000,"Company":"WIPRO",[100,201,301]:"Department ID"}
TypeError: unhashable type: 'list'

Built-in Dictionary Functions


A function is a method that can be used on a construct to yield a value. Additionally, the
construct is unaltered. A few of the Python methods can be combined with a Python
dictionary.

The built-in Python dictionary methods are listed below, along with a brief description.

○ len()

The dictionary's length is returned via the len() function in Python. The string is
lengthened by one for each key-value pair.

Code

1. dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}


2. len(dict)

Output

○ any()

Like how it does with lists and tuples, the any() method returns True indeed if one
dictionary key does have a Boolean expression that evaluates to True.

Code

1. dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}


2. any({'':'','':'','3':''})

Output

True

○ all()
Unlike in any() method, all() only returns True if each of the dictionary's keys contain a
True Boolean value.

Code

1. dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}


2. all({1:'',2:'','':''})

Output

False

○ sorted()

Like it does with lists and tuples, the sorted() method returns an ordered series of the
dictionary's keys. The ascending sorting has no effect on the original Python dictionary.

Code

1. dict = {7: "Ayan", 5: "Bunny", 8: "Ram", 1: "Bheem"}


2. sorted(dict)

Output

[ 1, 5, 7, 8]

Built-in Dictionary methods

The built-in python dictionary methods along with the description and Code are given
below.

○ clear()

It is mainly used to delete all the items of the dictionary.

Code
1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # clear() method
4. dict.clear()
5. print(dict)

Output

{}

○ copy()

It returns a shallow copy of the dictionary which is created.

Code

1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # copy() method
4. dict_demo = dict.copy()
5. print(dict_demo)

Output

{1: 'Hcl', 2: 'WIPRO', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}

○ pop()

It mainly eliminates the element using the defined key.

Code

1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # pop() method
4. dict_demo = dict.copy()
5. x = dict_demo.pop(1)
6. print(x)

Output

{2: 'WIPRO', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}

popitem()

removes the most recent key-value pair entered

Code

1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # popitem() method
4. dict_demo.popitem()
5. print(dict_demo)

Output

{1: 'Hcl', 2: 'WIPRO', 3: 'Facebook'}

○ keys()

It returns all the keys of the dictionary.

Code

1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # keys() method
4. print(dict_demo.keys())

Output

dict_keys([1, 2, 3, 4, 5])

○ items()

It returns all the key-value pairs as a tuple.

Code

1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # items() method
4. print(dict_demo.items())

Output

dict_items([(1, 'Hcl'), (2, 'WIPRO'), (3, 'Facebook'), (4, 'Amazon'), (5, 'Flipkart')])

○ get()

It is used to get the value specified for the passed key.

Code

1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # get() method
4. print(dict_demo.get(3))
Output

Facebook

○ update()

It mainly updates all the dictionary by adding the key-value pair of dict2 to this
dictionary.

Code

1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # update() method
4. dict_demo.update({3: "TCS"})
5. print(dict_demo)

Output

{1: 'Hcl', 2: 'WIPRO', 3: 'TCS'}

○ values()

It returns all the values of the dictionary with respect to given input.

Code

1. # dictionary methods
2. dict = {1: "Hcl", 2: "WIPRO", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
3. # values() method
4. print(dict_demo.values())

Output
dict_values(['Hcl', 'WIPRO', 'TCS'])

Iterate a Dictionary in Python


1. Using the inbuilt Methods

Code:

1. dictionary = {1: 'A', 2: 'B', 3: 'C'}


2. print ("Keys in the dictionary: ", dictionary. keys ())
3. print ("Values in the dictionary: ", dictionary. values ())
4. print ("The data stored in the dictionary: ", dictionary. items ())

Output:

Methods used in the code:

1. Dictionary.keys()

Returns the list of keys in the dictionary

2. Dictionary.values()

Returns the list of values in the dictionary

3. Dictionary.items()

Returns the list of all the key-value pairs as tuples in the dictionary

Understanding:

We just used the methods already defined in Python to manipulate a dictionary in the
code. In the first statement, a dictionary is created. In the next three statements, we
used .keys(), .values() and .items() to prints the keys, values and the (key: value) pairs in
the dictionary.

2. Using the basic Functionality of a Dictionary:

Code:

1. dictionary = {1: 'A', 2: 'B', 3: 'C'}


2. print ("The dictionary is: ", dictionary)
3. print ("Keys in the dictionary: ")
4. for i in dictionary:
5. print (i)
6. print ("Values in the dictionary: ")
7. for i in dictionary:
8. print (dictionary [i])

Output:

Understanding:

There are two important points to be grasped from the above code:

1. If we iterate a variable 'i' over a dictionary in Python, the dictionary's keys will be
traversed.

2. Now, if we want the values the keys hold, we need to ask the dictionary for which
we use- dictionary [key].
These are the two things we've done in the code. First, we declared a dictionary and
printed it. Then, we traversed through the dictionary's keys using the variable 'i'. In the
next loop, we traversed through the keys and printed their values:

We can use the same loop for printing both keys and values:

1. for i in dictionary:
2. print (i, end = ' ')
3. print (dictionary [i], end = ' ')
4. print ()

Output:

3. Iterating items ():

We've already seen the method items (). We used it to print all the (key: value) pairs in
the dictionary as a list of tuples. For a more clear representation of every key-value pair
in the dictionary, we can iterate a variable on the method:

Code:

1. dictionary = {1: 'A', 2: 'B', 3: 'C'}


2. print ("The dictionary is: ", dictionary)
3. for i in dictionary. items ():
4. print (i)

Output:
One Program using all types of Iteration Methods:
1. dictionary = {1: 'Hydrogen', 2: 'Helium', 3: 'Lithium'}
2. print ("\nThe dictionary: ", dictionary)
3. print ("\n")
4. print ("Without using the inbuilt functions: ")
5. print ("Keys and values in the dictionary: ")
6. for i in dictionary:
7. print ('key: ', i, end = ' ')
8. print ('value: ', dictionary [i], end = ' ')
9. print ()
10. print ("\nUsing the inbuilt functions: ")
11. print ("Keys in the dictionary: ", dictionary. keys ())
12. print ("Values in the dictionary: ", dictionary. values ())
13. print ("The data stored in the dictionary: ", dictionary. items ())
14. print ("\nTuple-wise representation: ")
15. for i in dictionary. items ():
16. print (i)

Output:
Summary:
In this Tutorial, we discussed:

1. Given a dictionary, how to iterate over all the keys?

2. Given a dictionary, how to iterate over all the values?

3. Iterating over the dictionary with the use of inbuilt Python methods and without
the use of the inbuilt methods.

4. Given a key, how to find the value it is holding?

5. Tuple arrangement of all the key-value pairs in the dictionary using .items ().

Python Tuples
A comma-separated group of items is called a Python triple. The ordering, settled items,
and reiterations of a tuple are to some degree like those of a rundown, but in contrast to
a rundown, a tuple is unchanging.
The main difference between the two is that we cannot alter the components of a tuple
once they have been assigned. On the other hand, we can edit the contents of a list.

Example

1. ("Suzuki", "Audi", "BMW"," Skoda ") is a tuple.

Features of Python Tuple

○ Tuples are an immutable data type, meaning their elements cannot be changed
after they are generated.

○ Each element in a tuple has a specific order that will never change because
tuples are ordered sequences.

Forming a Tuple:

All the objects-also known as "elements"-must be separated by a comma, enclosed in


parenthesis (). Although parentheses are not required, they are recommended.

Any number of items, including those with various data types (dictionary, string, float,
list, etc.), can be contained in a tuple.

Code

1. # Python program to show how to create a tuple


2. # Creating an empty tuple
3. empty_tuple = ()
4. print("Empty tuple: ", empty_tuple)
5.
6. # Creating tuple having integers
7. int_tuple = (4, 6, 8, 10, 12, 14)
8. print("Tuple with integers: ", int_tuple)
9.
10. # Creating a tuple having objects of different data types
11. mixed_tuple = (4, "Python", 9.3)
12. print("Tuple with different data types: ", mixed_tuple)
13.
14. # Creating a nested tuple
15. nested_tuple = ("Python", {4: 5, 6: 2, 8:2}, (5, 3, 5, 6))
16. print("A nested tuple: ", nested_tuple)

Output:

Empty tuple: ()
Tuple with integers: (4, 6, 8, 10, 12, 14)
Tuple with different data types: (4, 'Python', 9.3)
A nested tuple: ('Python', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))

Parentheses are not necessary for the construction of multiples. This is known as triple
pressing.

Code

1. # Python program to create a tuple without using parentheses


2. # Creating a tuple
3. tuple_ = 4, 5.7, "Tuples", ["Python", "Tuples"]
4. # Displaying the tuple created
5. print(tuple_)
6. # Checking the data type of object tuple_
7. print(type(tuple_) )
8. # Trying to modify tuple_
9. try:
10. tuple_[1] = 4.2
11. except:
12. print(TypeError )

Output:
(4, 5.7, 'Tuples', ['Python', 'Tuples'])
<class 'tuple'>
<class 'TypeError'>

The development of a tuple from a solitary part may be complex.

Essentially adding a bracket around the component is lacking. A comma must separate
the element to be recognized as a tuple.

Code

1. # Python program to show how to create a tuple having a single element


2. single_tuple = ("Tuple")
3. print( type(single_tuple) )
4. # Creating a tuple that has only one element
5. single_tuple = ("Tuple",)
6. print( type(single_tuple) )
7. # Creating tuple without parentheses
8. single_tuple = "Tuple",
9. print( type(single_tuple) )

Output:

<class 'str'>
<class 'tuple'>
<class 'tuple'>

Accessing Tuple Elements


A tuple's objects can be accessed in a variety of ways.

Indexing
Indexing We can use the index operator [] to access an object in a tuple, where the index
starts at 0.

The indices of a tuple with five items will range from 0 to 4. An Index Error will be raised
assuming we attempt to get to a list from the Tuple that is outside the scope of the
tuple record. An index above four will be out of range in this scenario.

Because the index in Python must be an integer, we cannot provide an index of a


floating data type or any other type. If we provide a floating index, the result will be
TypeError.

The method by which elements can be accessed through nested tuples can be seen in
the example below.

Code

1. # Python program to show how to access tuple elements


2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Collection")
4. print(tuple_[0])
5. print(tuple_[1])
6. # trying to access element index more than the length of a tuple
7. try:
8. print(tuple_[5])
9. except Exception as e:
10. print(e)
11. # trying to access elements through the index of floating data type
12. try:
13. print(tuple_[1.0])
14. except Exception as e:
15. print(e)
16. # Creating a nested tuple
17. nested_tuple = ("Tuple", [4, 6, 2, 6], (6, 2, 6, 7))
18.
19. # Accessing the index of a nested tuple
20. print(nested_tuple[0][3])
21. print(nested_tuple[1][1])

Output:

Python
Tuple
tuple index out of range
tuple indices must be integers or slices, not float
l
6

○ Negative Indexing

Python's sequence objects support negative indexing.

The last thing of the assortment is addressed by - 1, the second last thing by - 2, etc.

Code

1. # Python program to show how negative indexing works in Python tuples


2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Collection")
4. # Printing elements using negative indices
5. print("Element at -1 index: ", tuple_[-1])
6. print("Elements between -4 and -1 are: ", tuple_[-4:-1])

Output:

Element at -1 index: Collection


Elements between -4 and -1 are: ('Python', 'Tuple', 'Ordered')

Slicing
Tuple slicing is a common practice in Python and the most common way for
programmers to deal with practical issues. Look at a tuple in Python. Slice a tuple to
access a variety of its elements. Using the colon as a straightforward slicing operator (:)
is one strategy.

To gain access to various tuple elements, we can use the slicing operator colon (:).

Code

1. # Python program to show how slicing works in Python tuples


2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
4. # Using slicing to access elements of the tuple
5. print("Elements between indices 1 and 3: ", tuple_[1:3])
6. # Using negative indexing in slicing
7. print("Elements between indices 0 and -4: ", tuple_[:-4])
8. # Printing the entire tuple by using the default start and end values.
9. print("Entire tuple: ", tuple_[:])

Output:

Elements between indices 1 and 3: ('Tuple', 'Ordered')


Elements between indices 0 and -4: ('Python', 'Tuple')
Entire tuple: ('Python', 'Tuple', 'Ordered', 'Immutable', 'Collection', 'Objects')

Deleting a Tuple
A tuple's parts can't be modified, as was recently said. We are unable to eliminate or
remove tuple components as a result.

However, the keyword del can completely delete a tuple.

Code

1. # Python program to show how to delete elements of a Python tuple


2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
4. # Deleting a particular element of the tuple
5. try:
6. del tuple_[3]
7. print(tuple_)
8. except Exception as e:
9. print(e)
10. # Deleting the variable from the global space of the program
11. del tuple_
12. # Trying accessing the tuple after deleting it
13. try:
14. print(tuple_)
15. except Exception as e:
16. print(e)

Output:

'tuple' object does not support item deletion


name 'tuple_' is not defined

Repetition Tuples in Python

Code

1. # Python program to show repetition in tuples


2. tuple_ = ('Python',"Tuples")
3. print("Original tuple is: ", tuple_)
4. # Repeting the tuple elements
5. tuple_ = tuple_ * 3
6. print("New tuple is: ", tuple_)
Output:

Original tuple is: ('Python', 'Tuples')


New tuple is: ('Python', 'Tuples', 'Python', 'Tuples', 'Python', 'Tuples')

Tuple Methods

Like the list, Python Tuples is a collection of immutable objects. There are a few ways to
work with tuples in Python. With some examples, this essay will go over these two
approaches in detail.

The following are some examples of these methods.

○ Count () Method

The times the predetermined component happens in the Tuple is returned by the count
() capability of the Tuple.

Code

1. # Creating tuples
2. T1 = (0, 1, 5, 6, 7, 2, 2, 4, 2, 3, 2, 3, 1, 3, 2)
3. T2 = ('python', 'java', 'python', 'Tpoint', 'python', 'java')
4. # counting the appearance of 3
5. res = T1.count(2)
6. print('Count of 2 in T1 is:', res)
7. # counting the appearance of java
8. res = T2.count('java')
9. print('Count of Java in T2 is:', res)

Output:

Count of 2 in T1 is: 5
Count of java in T2 is: 2
Index() Method:

The Index() function returns the first instance of the requested element from the Tuple.

Parameters:

○ The thing that must be looked for.

○ Start: (Optional) the index that is used to begin the final (optional) search: The
most recent index from which the search is carried out

○ Index Method

Code

1. # Creating tuples
2. Tuple_data = (0, 1, 2, 3, 2, 3, 1, 3, 2)
3. # getting the index of 3
4. res = Tuple_data.index(3)
5. print('First occurrence of 1 is', res)
6. # getting the index of 3 after 4th
7. # index
8. res = Tuple_data.index(3, 4)
9. print('First occurrence of 1 after 4th index is:', res)

Output:

First occurrence of 1 is 2
First occurrence of 1 after 4th index is: 6

Tuple Membership Test

Utilizing the watchword, we can decide whether a thing is available in the given Tuple.

Code
1. # Python program to show how to perform membership test for tuples
2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Ordered")
4. # In operator
5. print('Tuple' in tuple_)
6. print('Items' in tuple_)
7. # Not in operator
8. print('Immutable' not in tuple_)
9. print('Items' not in tuple_)

Output:

True
False
False
True

Iterating Through a Tuple

A for loop can be used to iterate through each tuple element.

Code

1. # Python program to show how to iterate over tuple elements


2. # Creating a tuple
3. tuple_ = ("Python", "Tuple", "Ordered", "Immutable")
4. # Iterating over tuple elements using a for loop
5. for item in tuple_:
6. print(item)

Output:

Python
Tuple
Ordered
Immutable

Tuples have the following advantages over lists:

○ Triples take less time than lists do.

○ Due to tuples, the code is protected from accidental modifications. It is desirable


to store non-changing information in "tuples" instead of "records" if a program
expects it.

○ A tuple can be used as a dictionary key if it contains immutable values like


strings, numbers, or another tuple. "Lists" cannot be utilized as dictionary keys
because they are mutable.

You might also like