0% found this document useful (0 votes)
2 views

unit-3 py

This document provides an introduction to lists in Python, covering list creation, basic operations, and methods for adding, accessing, and removing elements. It also discusses advanced topics such as slicing, negative indexing, and the use of tuples and dictionaries. Several example programs and lab exercises are included to illustrate the concepts.

Uploaded by

mukilap6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

unit-3 py

This document provides an introduction to lists in Python, covering list creation, basic operations, and methods for adding, accessing, and removing elements. It also discusses advanced topics such as slicing, negative indexing, and the use of tuples and dictionaries. Several example programs and lab exercises are included to illustrate the concepts.

Uploaded by

mukilap6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Unit -3

Introduction to Lists - List literals-Basic list operators-Replacing an Element in a List-


Example program to Replace an Element in a List-List Methods for Inserting Elements-
Program to List Methods for Inserting Elements-Lab 7: Program to Transpose a Matrix-
Program to List Methods for Inserting Elements-List Methods for Removing Elements-
Searching a List-Sorting a List-Mutator Methods-Aliasing-Aliasing side effects-Equality:
Object Identity-Structural Equivalence-Lab 8: Using a List to Find the Median of a Set of
Numbers- Program using sorting and searching-Tuples-Creation of several tuples-
Dictionaries-Dictionary Literals-Adding Keys and Replacing Values-Accessing Values-
Removing Keys-Traversing a Dictionary-Lab 9: When the user enters a statement, the
program responds in one of two ways: 1 With a randomly chosen hedge, such as “Please
tell me more.” 2 By changing some key words in the user’s input string and appending this
string to a randomly chosen qualifier. Thus, to “My teacher always plays favorites,” the
program might reply, “Why do you say that your teacher always plays favorites?”
Python List

The list is a sequence data type which is used to store the collection of data.
L = [20, ‘aabb’,35.43,[‘e’,’b’,’m’]]

Ordered: Maintain the order of the data insertion


Changeable: List is mutable and we can modify items
Heterogeneous: List an contain data of different types
Contains duplicate: Allows duplicate data

Example of list in Python


Here we are creating Python List using [].
ex =["apple", "banana", "orange"]
print(ex)
Output:

"apple", "banana", "orange

Lists are the simplest containers that are an integral part of the Python language. Lists need
not be homogeneous always which makes it the most powerful tool in Python. A single list
may contain different data types like Integers, Strings, as well as Objects. Lists are mutable,
and hence, they can be altered even after their creation.

Creating a List in Python


Lists in Python can be created by just placing the sequence inside the square brackets [].
List = []
print(List)
print("Blank List: ")

# Creating a List of numbers


List = [10, 20, 14]
print("\nList of numbers: ")
print(List)

# Creating a List of strings and accessing


# using index
List = ["apple", "orange", "banana"]
print("\nList Items: ")
print(List[0])
print(List[2])

Output
Blank List:
[]

List of numbers:
[10, 20, 14]

List Items:
apple
banana

Creating a list with multiple distinct or duplicate elements

A list may contain duplicate values with their distinct positions and hence, multiple distinct
or duplicate values can be passed as a sequence at the time of list creation.
# Creating a List with
# the use of Numbers
# (Having duplicate values)
List=[1, 2, 4, 4, 3, 3, 3, 6, 5]
print("\nList with the use of Numbers: ")
print(List)

Length of a List
In order to find the number of items present in a list, we can use the len() function.
my_list=[1,2,3]
print(len(my_list))
# output 3

# Creating a List with


# mixed type of values having numbers and strings
List=[1, 2, 'apple', 4, 'For', 6, 'apple']
print("\nList with the use of Mixed Values: ")
print(List)
List with the use of Numbers:
[1, 2, 4, 4, 3, 3, 3, 6, 5]

List with the use of Mixed Values:


[1, 2, 'apple', 4, 'For', 6, 'apple']

Accessing elements from the List


In order to access the list items refer to the index number. Use the index operator [ ] to
access an item in a list. The index must be an integer. Nested lists are accessed using nested
indexing.
Example 1: Accessing elements from list
# Python program to demonstrate
# accessing of element from list

# Creating a List with


# the use of multiple values
List=["Geeks", "For", "Geeks"]

# accessing a element from the


# list using index number
print("Accessing a element from the list")
print(List[0])
print(List[2])
Output
Accessing a element from the list
Geeks
Geeks
Example 2: Accessing elements from a multi-dimensional list
# Creating a Multi-Dimensional List
# (By Nesting a list inside a List)
List=[['Geeks', 'For'], ['Geeks']]

# accessing an element from the


# Multi-Dimensional List using
# index number
print("Accessing a element from a Multi-Dimensional list")
print(List[0][1])
print(List[1][0])
Output
Accessing a element from a Multi-Dimensional list
For
Geeks

Negative indexing

In Python, negative sequence indexes represent positions from the end of the array. Instead
of having to compute the offset as in List[len(List)-3], it is enough to just write List[-3].
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the
second-last item, etc.
List=[1, 2, 'python', 4, 'For', 6, 'python']

# accessing an element using


# negative indexing
print("Accessing element using negative indexing")

# print the last element of list


print(List[-1])

# print the third last element of list


print(List[-3])
Output
Accessing element using negative indexing
python
For

Getting the size of Python list


Pythonlen() is used to get the length of the list.
# Creating a List
List1 =[]
print(len(List1))

# Creating a List of numbers


List2 =[10, 20, 14]
print(len(List2))
Output
0
3

Taking Input of a Python List


We can take the input of a list of elements as string, integer, float, etc. But the default one
is a string.
# Python program to take space
# separated input as a string
# split and store it to a list
# and print the string list

# input the list as string


string = input("Enter elements (Space-Separated): ")

# split the strings and store it to a list


lst = string.split()
print('The list is:', lst) # printing the list
Output:
Enter elements: GEEKS FOR GEEKS
The list is: ['GEEKS', 'FOR', 'GEEKS']
# input size of the list
n = int(input("Enter the size of list : "))
# store integers in a list using map,
# split and strip functions
lst = list(map(int, input("Enter the integer\
elements:").strip().split()))[:n]

# printing the list


print('The list is:', lst)
Output:
Enter the size of list : 4
Enter the integer elements: 6 3 9 10
The list is: [6, 3, 9, 10]
Adding Elements to a Python List
Method 1: Using append() method
Elements can be added to the List by using the built-in append() function. Only one
element at a time can be added to the list by using the append() method, for the addition of
multiple elements with the append() method, loops are used. Tuples can also be added to
the list with the use of the append method because tuples are immutable. Unlike Sets, Lists
can also be added to the existing list with the use of the append() method.
# Python program to demonstrate
# Addition of elements in a List

# Creating a List
List=[]
print("Initial blank List: ")
print(List)

# Addition of Elements
# in the List
List.append(1)
List.append(2)
List.append(4)
print("\nList after Addition of Three elements: ")
print(List)

# Adding elements to the List


# using Iterator
fori inrange(1, 4):
List.append(i)
print("\nList after Addition of elements from 1-3: ")
print(List)

# Adding Tuples to the List


List.append((5, 6))
print("\nList after Addition of a Tuple: ")
print(List)

# Addition of List to a List


List2 =['For', 'Geeks']
List.append(List2)
print("\nList after Addition of a List: ")
print(List)
Output
Initial blank List:
[]

List after Addition of Three elements:


[1, 2, 4]

List after Addition of elements from 1-3:


[1, 2, 4, 1, 2, 3]
List after Addition of a Tuple:
[1, 2, 4, 1, 2, 3, (5, 6)]

List after Addition of a List:


[1, 2, 4, 1, 2, 3, (5, 6), ['For', 'Geeks']]
Complexities for Adding elements in a Lists(append() method):
Method 2: Using insert() method
append() method only works for the addition of elements at the end of the List, for the
addition of elements at the desired position, insert() method is used. Unlike append() which
takes only one argument, the insert() method requires two arguments(position, value).
# Python program to demonstrate
# Addition of elements in a List

# Creating a List
List=[1,2,3,4]
print("Initial List: ")
print(List)

# Addition of Element at
# specific Position
# (using Insert Method)
List.insert(3, 12)
List.insert(0, 'Geeks')
print("\nList after performing Insert Operation: ")
print(List)
Output
Initial List:
[1, 2, 3, 4]

List after performing Insert Operation:


['Geeks', 1, 2, 3, 12, 4]
Complexities for Adding elements in a Lists(insert() method):
Method 3: Using extend() method
Other than append() and insert() methods, there’s one more method for the Addition of
elements, extend(), this method is used to add multiple elements at the same time at the
end of the list.
Note: append() and extend() methods can only add elements at the end.
# Python program to demonstrate
# Addition of elements in a List

# Creating a List
List=[1, 2, 3, 4]
print("Initial List: ")
print(List)

# Addition of multiple elements


# to the List at the end
# (using Extend Method)
List.extend([8, 'Geeks', 'Always'])
print("\nList after performing Extend Operation: ")
print(List)
Output
Initial List:
[1, 2, 3, 4]

List after performing Extend Operation:


[1, 2, 3, 4, 8, 'Geeks', 'Always']

Reversing a List
A list can be reversed by using the reverse() method in Python.
# Reversing a list
mylist =[1, 2, 3, 4, 5, 'Geek', 'Python']
mylist.reverse()
print(mylist)
Output
['Python', 'Geek', 5, 4, 3, 2, 1]

Removing Elements from the List


Method 1: Using remove() method
Elements can be removed from the List by using the built-in remove() function but an Error
arises if the element doesn’t exist in the list. Remove() method only removes one element
at a time, to remove a range of elements, the iterator is used. The remove() method removes
the specified item.
Note: Remove method in List will only remove the first occurrence of the searched
element.
Example 1:
# Python program to demonstrate
# Removal of elements in a List

# Creating a List
List=[1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12]
print("Initial List: ")
print(List)

# Removing elements from List


# using Remove() method
List.remove(5)
List.remove(6)
print("\nList after Removal of two elements: ")
print(List)
Output
Initial List:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

List after Removal of two elements:


[1, 2, 3, 4, 7, 8, 9, 10, 11, 12]
Example 2:
# Creating a List
List=[1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12]
# Removing elements from List
# using iterator method
fori inrange(1, 5):
List.remove(i)
print("\nList after Removing a range of elements: ")
print(List)
Output
List after Removing a range of elements:
[5, 6, 7, 8, 9, 10, 11, 12]

Method 2: Using pop() method


pop() function can also be used to remove and return an element from the list, but by default
it removes only the last element of the list, to remove an element from a specific position
of the List, the index of the element is passed as an argument to the pop() method.
List=[1, 2, 3, 4, 5]

# Removing element from the


# Set using the pop() method
List.pop()
print("\nList after popping an element: ")
print(List)

# Removing element at a
# specific location from the
# Set using the pop() method
List.pop(2)
print("\nList after popping a specific element: ")
print(List)
Output
List after popping an element:
[1, 2, 3, 4]

List after popping a specific element:


[1, 2, 4]

Slicing of a List
We can get substrings and sublists using a slice. In Python List, there are multiple ways to
print the whole list with all the elements, but to print a specific range of elements from the
list, we use the Slice operation.
Slice operation is performed on Lists with the use of a colon(:).
To print elements from beginning to a range use:
[: Index]
To print elements from end-use:
[:-Index]
To print elements from a specific Index till the end use
[Index:]
To print the whole list in reverse order, use
[::-1]
Note – To print elements of List from rear-end, use Negative Indexes.

UNDERSTANDING SLICING OF LISTS:


pr[0] accesses the first item, 2.
pr[-4] accesses the fourth item from the end, 5.
pr[2:] accesses [5, 7, 11, 13], a list of items from third to last.
pr[:4] accesses [2, 3, 5, 7], a list of items from first to fourth.
pr[2:4] accesses [5, 7], a list of items from third to fifth.
pr[1::2] accesses [3, 7, 13], alternate items, starting from the second item.
# Python program to demonstrate
# Removal of elements in a List

# Creating a List
List=['G', 'E', 'E', 'K', 'S', 'F',
'O', 'R', 'G', 'E', 'E', 'K', 'S']
print("Initial List: ")
print(List)

# Print elements of a range


# using Slice operation
Sliced_List =List[3:8]
print("\nSlicing elements in a range 3-8: ")
print(Sliced_List)

# Print elements from a


# pre-defined point to end
Sliced_List =List[5:]
print("\nElements sliced from 5th "
"element till the end: ")
print(Sliced_List)

# Printing elements from


# beginning till end
Sliced_List =List[:]
print("\nPrinting all elements using slice operation: ")
print(Sliced_List)
Output
Initial List:
['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']
Slicing elements in a range 3-8:
['K', 'S', 'F', 'O', 'R']

Elements sliced from 5th element till the end:


['F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']

Printing all elements using slice operation:


['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']
Negative index List slicing
# Creating a List
List=['G', 'E', 'E', 'K', 'S', 'F',
'O', 'R', 'G', 'E', 'E', 'K', 'S']
print("Initial List: ")
print(List)

# Print elements from beginning


# to a pre-defined point using Slice
Sliced_List =List[:-6]
print("\nElements sliced till 6th element from last: ")
print(Sliced_List)

# Print elements of a range


# using negative index List slicing
Sliced_List =List[-6:-1]
print("\nElements sliced from index -6 to -1")
print(Sliced_List)

# Printing elements in reverse


# using Slice operation
Sliced_List =List[::-1]
print("\nPrinting List in reverse: ")
print(Sliced_List)
Output
Initial List:
['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']

Elements sliced till 6th element from last:


['G', 'E', 'E', 'K', 'S', 'F', 'O']

Elements sliced from index -6 to -1


['R', 'G', 'E', 'E', 'K']

Printing List in reverse:


['S', 'K', 'E', 'E', 'G', 'R', 'O', 'F', 'S', 'K', 'E', 'E', 'G']
List Comprehension
Python List comprehensions are used for creating new lists from other iterables like
tuples, strings, arrays, lists, etc. A list comprehension consists of brackets containing the
expression, which is executed for each element along with the for loop to iterate over each
element.
Syntax:
newList = [ expression(element) for element in oldList if condition ]
Example:
# Python program to demonstrate list
# comprehension in Python

# below list contains square of all


# odd numbers from range 1 to 10
odd_square =[x **2forx inrange(1, 11) ifx %2==1]
print(odd_square)
Output
[1, 9, 25, 49, 81]
For better understanding, the above code is similar to as follows:
# for understanding, above generation is same as,
odd_square =[]

forx inrange(1, 11):


ifx %2==1:
odd_square.append(x**2)

print(odd_square)
Output
[1, 9, 25, 49, 81]
List Methods
Function Description
Append() Add an element to the end of the list
Extend() Add all elements of a list to another list
Insert() Insert an item at the defined index
Remove() Removes an item from the list
Clear() Removes all items from the list
Index() Returns the index of the first matched item
Count() Returns the count of the number of items passed as an argument
Sort() Sort items in a list in ascending order
Reverse() Reverse the order of items in the list
copy() Returns a copy of the list

Built-in functions with List


Function Description
apply a particular function passed in its argument to all of the list
reduce() elements stores the intermediate result and only returns the final
summation value
sum() Sums up the numbers in the list
Returns an integer representing the Unicode code point of the given
ord()
Unicode character
cmp() This function returns 1 if the first list is “greater” than the second list
max() return maximum element of a given list
min() return minimum element of a given list
Function Description
all() Returns true if all element is true or if the list is empty
return true if any element of the list is true. if the list is empty, return
any()
false
len() Returns length of the list or size of the list
enumerate() Returns enumerate object of the list
apply a particular function passed in its argument to all of the list
accumulate()
elements returns a list containing the intermediate results
filter() tests if each element of a list is true or not
returns a list of the results after applying the given function to each item
map()
of a given iterable
This function can have any number of arguments but only one
lambda()
expression, which is evaluated and returned.
List Slicing
Slicing a list implies, accessing a range of elements in a list. For example, if we want to get
the elements in the position from 3 to 7, we can use the slicing method. We can even modify
the values in a range by using this slicing technique.
The below is the syntax for list slicing.
listname[start_index:end_index: step]
The start_index denotes the index position from where the slicing should begin and the
end_index parameter denotes the index positions till which the slicing should be done.
The step allows you to take each nth-element within a start_index:end_index range.
Example
my_list = [10, 20, 'Jessa', 12.50, 'Emma', 25, 50]
# Extracting a portion of the list from 2nd till 5th element
print(my_list[2:5])
# Output ['Jessa', 12.5, 'Emma']

Example
my_list = [5, 8, 'Tom', 7.50, 'Emma']

# slice first four items


print(my_list[:4])
# Output [5, 8, 'Tom', 7.5]

# print every second element


# with a skip count 2
print(my_list[::2])
# Output [5, 'Tom', 'Emma']

# reversing the list


print(my_list[::-1])
# Output ['Emma', 7.5, 'Tom', 8, 5]

# Withoutend_value
# Stating from 3nd item to last item
print(my_list[3:])
# Output [7.5, 'Emma']

Python Dictionary
An effective data structure for storing data in Python is dictionaries, in which can simulate
the real-life data arrangement where some specific value exists for some particular key.
Python Dictionary is used to store the data in a key-value pair format.
It is the mutable data-structure.
The elements Keys and values is employed to create the dictionary.
Keys must consist of just one element.
Value can be any type such as list, tuple, integer, etc.
In other words, we can say that a dictionary is the collection of key-value pairs where the
value can be of any Python object. In contrast, the keys are the immutable Python object,
i.e., Numbers, string, or tuple. Dictionary entries are ordered as of Python version 3.7. In
Python 3.6 and before, dictionaries are generally unordered.
Creating the Dictionary
The simplest approach to create a Python dictionary is by using curly brackets {}, but there
are other methods as well. The dictionary can be created by using multiple key-value pairs
enclosed with the curly brackets {}, and each key is separated from its value by the colon
(:). The syntax to define the dictionary is given below.
Dict = {"Name": "Chris", "Age": 20}
In the above dictionary Dict, The keys Name and Age are the strings which comes under
the category of an immutable object.
Let's see an example to create a dictionary and print its content.
Code
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
Output
<class 'dict'>
printing Employee data ....
{'Name': 'John', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'}
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
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Microsoft', 2: 'Google', 3:'Facebook'})
print("\nCreate Dictionary by using dict(): ")
print(Dict)

# Creating a Dictionary
# with each item as a Pair
Dict = dict([(4, 'Praneeth'), (2, 'Varma')])
print("\nDictionary with each item as a pair: ")
print(Dict)
Output
Empty Dictionary:
{}

Create Dictionary by using dict():


{1: 'Microsoft', 2: 'Google', 3: 'Facebook'}

Dictionary with each item as a pair:


{4: 'Praneeth', 2: 'Varma'}
Accessing the dictionary values
We've discussed about using indexing to access data stored in lists and tuples. However,
because the dictionary's keys are distinct from one another, it is possible to get the values
by utilising the keys. The dictionary values can be accessed in the following way.
Code
Employee = {"Name": "David", "Age": 30, "salary":55000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
print("Salary : %d" %Employee["salary"])
print("Company : %s" %Employee["Company"])
Output
<class 'dict'>
printing Employee data ....
Name : David
Age : 30
Salary : 55000
Company : GOOGLE
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 its values can be updated by using the specific
keys. The value can be updated along with key Dict[key] = value. The update() method is
also used to update an existing value.
Note: If the key-value already present in the dictionary, the value gets updated.
Otherwise, the new keys added in the dictionary.
Let's see an example to update the dictionary values.
Example - 1:
Code
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Adding elements to dictionary one at a time


Dict[0] = 'Peter'
Dict[2] = 'Joseph'
Dict[3] = 'Ricky'
print("\nDictionary after adding 3 elements: ")
print(Dict)

# Adding set of values


# with a single Key
# The Emp_ages doesn't exist to dictionary
Dict['Emp_ages'] = 20, 33, 24
print("\nDictionary after adding 3 elements: ")
print(Dict)

# Updating existing Key's Value


Dict[3] = 'JavaTpoint'
print("\nUpdated key value: ")
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
Employee = {"Name": "David", "Age": 30, "salary":55000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Enter the details of the new employee....");
Employee["Name"] = input("Name: ");
Employee["Age"] = int(input("Age: "));
Employee["salary"] = int(input("Salary: "));
Employee["Company"] = input("Company:");
print("printing the new data");
print(Employee)
Output
<class 'dict'>
printing Employee data ....
{'Name': 'David', 'Age': 30, 'salary': 55000, 'Company': 'GOOGLE'}
Enter the details of the new employee....
Name: Rahul
Age: 28
Salary: 36000
Company:Microsoft
printing the new data
{'Name': 'Rahul', 'Age': 28, 'salary': 36000, 'Company': 'Microsoft'}
Deleting Elements using del Keyword
The items of the dictionary can be deleted by using the del keyword as given below.
Code
Employee = {"Name": "David", "Age": 30, "salary":55000,"Company":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Deleting some of the employee data")
del Employee["Name"]
del Employee["Company"]
print("printing the modified information ")
print(Employee)
print("Deleting the dictionary: Employee");
del Employee
print("Lets try to print it again ");
print(Employee)
Output
<class 'dict'>
printing Employee data ....
{'Name': 'David', 'Age': 30, 'salary': 55000, 'Company': 'GOOGLE'}
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
The pop() method accepts the key as an argument and remove the associated value.
Consider the following example.
Code
# Creating a Dictionary
Dict = {1: 'JavaTpoint', 2: 'Learning', 3: 'Website'}
# Deleting a key
# using pop() method
pop_key = Dict.pop(2)
print(Dict)
Output
{1: 'JavaTpoint', 3: 'Website'}
Python also provides a built-in methods popitem() and clear() method for remove elements
from the dictionary. The popitem() removes the arbitrary element from a dictionary,
whereas the clear() method removes all elements to the whole dictionary.
Iterating Dictionary
A dictionary can be iterated using for loop as given below.
Example 1
Code
# for loop to print all the keys of a dictionary
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
for x in Employee:
print(x)
Output
Name
Age
salary
Company
Example 2
Code
#for loop to print all the values of the dictionary
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"} for x
in Employee:
print(Employee[x])
Output
John
29
25000
GOOGLE
Example - 3
Code
#for loop to print the values of the dictionary by using values() method.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
for x in Employee.values():
print(x)
Output
John
29
25000
GOOGLE
Example 4
Code
#for loop to print the items of the dictionary by using items() method
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
for x in Employee.items():
print(x)
Output
('Name', 'John')
('Age', 29)
('salary', 25000)
('Company', 'GOOGLE')
Properties of Dictionary Keys
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
Employee={"Name":"John","Age":29,"Salary":25000,"Company":"GOOGLE","Name":
"John"}
for x,y in Employee.items():
print(x,y)
Output
Name John
Age 29
Salary 25000
Company GOOGLE
In [ ]:
In python, the key cannot be any mutable object. We can use numbers, strings, or tuples as
the key, but we cannot use any mutable object like the list as the key in the dictionary.
Consider the following example.
Code
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE",[100,2
01,301]:"Department ID"}
for x,y in Employee.items():
print(x,y)
Output
Traceback (most recent call last):
File "dictionary.py", line 1, in
Employee = {"Name": "John", "Age": 29,
"salary":25000,"Company":"GOOGLE",[100,201,301]:"Department ID"}
TypeError: unhashable type: 'list'
Built-in Dictionary Functions
A technique that may be used on a construct to produce a value is known as a function.
Additionally, it doesn't change the construct. A Python dictionary can be used with a
handful of the methods that Python provides.
The built-in python dictionary methods along with the description are given below.
len()
Python's len() method returns the dictionary's length. Each key-value pair lengthens the
string by one.
Code
dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}
len(dict)
Output
4
any()
The any() method returns True indeed if one dictionary key does have a Boolean expression
of True, much like it does for lists and tuples.
Code
dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}
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
dict = {1: "Ayan", 2: "Bunny", 3: "Ram", 4: "Bheem"}
all({1:'',2:'','':''})
Output
False
sorted()
The sorted() method returns an ordered series of the dictionary's keys, much like it does
with lists as well as tuples. The initial Python dictionary is not changed by the ascending
sorting.
Code
dict = {7: "Ayan", 5: "Bunny", 8: "Ram", 1: "Bheem"}
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 used to delete all the items of the dictionary.
Code
# dictionary methods
dict = {1: "Microsoft", 2: "Google", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# clear() method
dict.clear()
print(dict)
Output
{}
copy()
It returns a shallow copy of the dictionary.
Code
# dictionary methods
dict = {1: "Microsoft", 2: "Google", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# copy() method
dict_demo = dict.copy()
print(dict_demo)
Output
{1: 'Microsoft', 2: 'Google', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}
pop()
eliminates the element using the defined key.
Code
# dictionary methods
dict = {1: "Microsoft", 2: "Google", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# pop() method
dict_demo = dict.copy()
x = dict_demo.pop(1)
print(x)
Output
{2: 'Google', 3: 'Facebook', 4: 'Amazon', 5: 'Flipkart'}
popitem()
removes the most recent key-value pair entered
Code
# dictionary methods
dict = {1: "Microsoft", 2: "Google", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# popitem() method
dict_demo.popitem()
print(dict_demo)
Output
{1: 'Microsoft', 2: 'Google', 3: 'Facebook'}
keys()
It returns all the keys of the dictionary.
Code
# dictionary methods
dict = {1: "Microsoft", 2: "Google", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# keys() method
print(dict_demo.keys())
Output
dict_keys([1, 2, 3, 4, 5])
items()
It returns all the key-value pairs as a tuple.
Code
# dictionary methods
dict = {1: "Microsoft", 2: "Google", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# items() method
print(dict_demo.items())
Output
dict_items([(1, 'Microsoft'), (2, 'Google'), (3, 'Facebook'), (4, 'Amazon'), (5, 'Flipkart')])
get()
It is used to get the value specified for the passed key.
Code
# dictionary methods
dict = {1: "Microsoft", 2: "Google", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# get() method
print(dict_demo.get(3))
Output
Facebook
update()
It updates the dictionary by adding the key-value pair of dict2 to this dictionary.
Code
# dictionary methods
dict = {1: "Microsoft", 2: "Google", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# update() method
dict_demo.update({3: "TCS"})
print(dict_demo)
Output
{1: 'Microsoft', 2: 'Google', 3: 'TCS'}
values()
It returns all the values of the dictionary.
Code
# dictionary methods
dict = {1: "Microsoft", 2: "Google", 3: "Facebook", 4: "Amazon", 5: "Flipkart"}
# values() method
print(dict_demo.values())
Output
dict_values(['Microsoft', 'Google', 'TCS'])
Built-in Dictionary methods
The built-in python dictionary methods along with the description are given below.
SN Method Description
1 dic.clear() It is used to delete all the items of the
dictionary.
2 dict.copy() It returns a shallow copy of the dictionary.
3 dict.fromkeys(iterable, Create a new dictionary from the iterable
value = None, /) with the values equal to value.
4 dict.get(key, default = It is used to get the value specified for the
"None") passed key.
5 dict.has_key(key) It returns true if the dictionary contains the
specified key.
6 dict.items() It returns all the key-value pairs as a tuple.
7 dict.keys() It returns all the keys of the dictionary.
8 dict.setdefault(key,default= It is used to set the key to the default value
"None") if the key is not specified in the dictionary
9 dict.update(dict2) It updates the dictionary by adding the key-
value pair of dict2 to this dictionary.
10 dict.values() It returns all the values of the dictionary.
11 len()
12 popItem()
13 pop()
14 count()
15 index()

Python Tuples

A Python Tuple is a group of items that are separated by commas. The indexing,
nested objects, and repetitions of a tuple are somewhat like those of a list, however
unlike a list, a tuple is immutable.

The distinction between the two is that while we can edit the contents of a list, we
cannot alter the elements of a tuple once they have been assigned.

Example

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


Features of Python Tuple
Tuples are an immutable data type, which means that once they have been
generated, their elements cannot be changed.
Since tuples are ordered sequences, each element has a specific order that will
never change.

Creating of Tuple:

To create a tuple, all the objects (or "elements") must be enclosed in parenthesis (),
each one separated by a comma. Although it is not necessary to include
parentheses, doing so is advised.

A tuple can contain any number of items, including ones with different data types
(dictionary, string, float, list, etc.).

Code:

# Python program to show how to create a tuple


# Creating an empty tuple
empty_tuple = ()
print("Empty tuple: ", empty_tuple)

# Creating tuple having integers


int_tuple = (4, 6, 8, 10, 12, 14)
print("Tuple with integers: ", int_tuple)

# Creating a tuple having objects of different data types


mixed_tuple = (4, "Python", 9.3)
print("Tuple with different data types: ", mixed_tuple)

# Creating a nested tuple


nested_tuple = ("Python", {4: 5, 6: 2, 8:2}, (5, 3, 5, 6))
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))

Tuples can be constructed without using parentheses. This is known as triple


packing.

Code

# Python program to create a tuple without using parentheses


# Creating a tuple
tuple_ = 4, 5.7, "Tuples", ["Python", "Tuples"]
# Displaying the tuple created
print(tuple_)
# Checking the data type of object tuple_
print(type(tuple_) )
# Trying to modify tuple_
try:
tuple_[1] = 4.2
except:
print(TypeError )

Output:

(4, 5.7, 'Tuples', ['Python', 'Tuples'])


<class 'tuple'>
<class 'TypeError'>

The construction of a tuple from a single member might be hard.

Simply adding parenthesis around the element is insufficient. To be recognised as


a tuple, the element must be followed by a comma.

Code

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


single_tuple = ("Tuple")
print( type(single_tuple) )
# Creating a tuple that has only one element
single_tuple = ("Tuple",)
print( type(single_tuple) )
# Creating tuple without parentheses
single_tuple = "Tuple",
print( type(single_tuple) )

Output:

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

Accessing Tuple Elements

We can access the objects of a tuple in a variety of ways.

Indexing

To access an object of a tuple, we can use the index operator [], where indexing in
the tuple starts from 0.

A tuple with 5 items will have indices ranging from 0 to 4. An IndexError will be
raised if we try to access an index from the tuple that is outside the range of the
tuple index. In this case, an index above 4 will be out of range.
We cannot give an index of a floating data type or other kinds because the index in
Python must be an integer. TypeError will appear as a result if we give a floating
index.

The example below illustrates how indexing is performed in nested tuples to access
elements.

Code

# Python program to show how to access tuple elements


# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Collection")
print(tuple_[0])
print(tuple_[1])
# trying to access element index more than the length of a tuple
try:
print(tuple_[5])
except Exception as e:
print(e)
# trying to access elements through the index of floating data type
try:
print(tuple_[1.0])
except Exception as e:
print(e)
# Creating a nested tuple
nested_tuple = ("Tuple", [4, 6, 2, 6], (6, 2, 6, 7))

# Accessing the index of a nested tuple


print(nested_tuple[0][3])
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 item of the collection is represented by -1, the second last item by -2, and
so on.

Code

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


# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Collection")
# Printing elements using negative indices
print("Element at -1 index: ", tuple_[-1])
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

In Python, tuple slicing is a common practise and the most popular method for
programmers to handle practical issues. Think about a Python tuple. To access a
variety of elements in a tuple, you must slice it. One approach is to use the colon
as a straightforward slicing operator (:).

We can use a slicing operator, a colon (:), to access a range of tuple elements.

Code

# Python program to show how slicing works in Python tuples


# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
# Using slicing to access elements of the tuple
print("Elements between indices 1 and 3: ", tuple_[1:3])
# Using negative indexing in slicing
print("Elements between indices 0 and -4: ", tuple_[:-4])
# Printing the entire tuple by using the default start and end values.
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 components cannot be altered, as was previously said. As a result, we are


unable to get rid of or remove tuple components.

However, a tuple can be totally deleted with the keyword del.

Code

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


# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
# Deleting a particular element of the tuple
try:
del tuple_[3]
print(tuple_)
except Exception as e:
print(e)
# Deleting the variable from the global space of the program
del tuple_
# Trying accessing the tuple after deleting it
try:
print(tuple_)
except Exception as e:
print(e)

Output:

'tuple' object does not support item deletion


name 'tuple_' is not defined
Repetition Tuples in Python

Code

# Python program to show repetition in tuples


tuple_ = ('Python',"Tuples")
print("Original tuple is: ", tuple_)
# Repeting the tuple elements
tuple_ = tuple_ * 3
print("New tuple is: ", tuple_)

Output:

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


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

Python Tuples is a collection of immutable objects that is more like to a list. Python
offers a few ways to work with tuples. These two approaches will be thoroughly
covered in this essay with the aid of some examples.

Examples of these methods are given below.

Count () Method

The number of times the specified element occurs in the tuple is returned by the
count () function of Tuple.

Code
# Creating tuples
T1 = (0, 1, 5, 6, 7, 2, 2, 4, 2, 3, 2, 3, 1, 3, 2)
T2 = ('python', 'java', 'python', 'Tpoint', 'python', 'java')
# counting the appearance of 3
res = T1.count(2)
print('Count of 2 in T1 is:', res)
# counting the appearance of java
res = T2.count('java')
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 first instance of the requested element from the tuple is returned by the Index()
function.

Parameters:

The element to be looked for.

begin (Optional): the index used as the starting point for searching

final (optional): The last index up until which the search is conducted

Index() Method

Code

# Creating tuples
Tuple_data = (0, 1, 2, 3, 2, 3, 1, 3, 2)
# getting the index of 3
res = Tuple_data.index(3)
print('First occurrence of 1 is', res)
# getting the index of 3 after 4th
# index
res = Tuple_data.index(3, 4)
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

Using the in keyword, we can determine whether an item is present in the given
tuple or not.

Code

# Python program to show how to perform membership test for tuples


# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Ordered")
# In operator
print('Tuple' in tuple_)
print('Items' in tuple_)
# Not in operator
print('Immutable' not in tuple_)
print('Items' not in tuple_)

Output:

True
False
False
True
Iterating Through a Tuple

We can use a for loop to iterate through each element of a tuple.

Code

# Python program to show how to iterate over tuple elements


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

Output:

Python
Tuple
Ordered
Immutable
Changing a Tuple

Tuples, as opposed to lists, are immutable objects.


This suggests that we are unable to change a tuple's elements once they have been
defined. The nested elements of an element can be changed, though, if the element
itself is a changeable data type like a list.

A tuple can be assigned to many values (reassignment).

Code

# Python program to show that Python tuples are immutable objects


# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", [1,2,3,4])
# Trying to change the element at index 2
try:
tuple_[2] = "Items"
print(tuple_)
except Exception as e:
print( e )
# But inside a tuple, we can change elements of a mutable object
tuple_[-1][2] = 10
print(tuple_)
# Changing the whole tuple
tuple_ = ("Python", "Items")
print(tuple_)

Output:

'tuple' object does not support item assignment


('Python', 'Tuple', 'Ordered', 'Immutable', [1, 2, 10, 4])
('Python', 'Items')

To merge multiple tuples, we can use the + operator. Concatenation is the term for
this.

Using the * operator, we may also repeat a tuple's elements for a specified number
of times. This is already shown above.

The results of the operations + and * are new tuples.

Code

# Python program to show how to concatenate tuples


# Creating a tuple
tuple_ = ("Python", "Tuple", "Ordered", "Immutable")
# Adding a tuple to the tuple_
print(tuple_ + (4, 5, 6))

Output:

('Python', 'Tuple', 'Ordered', 'Immutable', 4, 5, 6)


Following are Some Advantages of Tuples over Lists:

Lists take longer than triples.

The code is protected from any unintentional changes thanks to tuples. It is


preferable to store non-changing data in "tuples" rather than "lists" if it is required
by a programme.

If a tuple includes immutable values like strings, numbers, or another tuple, it can
be used as a dictionary key. Since "lists" are mutable, they cannot be utilized as
dictionary keys.

You might also like