0% found this document useful (0 votes)
34 views12 pages

Chapter 3-3

Chapter 3 covers the data types in Python: lists, dictionaries, tuples, and sets. It explains the characteristics, syntax, and operations associated with each type, including examples of how to manipulate them. The chapter also includes implementations of stack and queue using lists, as well as various methods for dictionaries and tuples.

Uploaded by

ys5263791
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)
34 views12 pages

Chapter 3-3

Chapter 3 covers the data types in Python: lists, dictionaries, tuples, and sets. It explains the characteristics, syntax, and operations associated with each type, including examples of how to manipulate them. The chapter also includes implementations of stack and queue using lists, as well as various methods for dictionaries and tuples.

Uploaded by

ys5263791
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/ 12

LIST, DICTIONARY, TUPLE & SET Chapter 3

Chapter 3

LIST DATA TYPE


▪ A List is a collection which is ordered and changeable / mutable.
▪ It allows duplicate members.
▪ A list is similar to array.
▪ Lists are represented by square brackets [] and the elements are separated
by comma.
▪ The main difference between a list and an array is that a list can store
different data type elements, but an array can store only one type of
elements.
▪ List can grow dynamically in memory but the size of array is fixed and they
cannot grow dynamically.

The following are the characteristics of a Python list:


➢ Values are ordered
➢ Mutable
➢ A list can hold any number of values
➢ A list can add, remove, and modify the values

Syntax:
List-var =[ele1,ele2, …,elen]

Example,
k=[1,2,3,4,5,”python”]

List Operations:
Let us consider the list k=[1,2,3,4,5,”PYTHON”]
1. Indexing:
▪ For accessing an element of the list, indexing is used.
▪ List index starts from 0 in left to right method.
▪ Working from right to left, the first element has the index -1, the next one
-2 and so on, but left most element is still 0.
Example:
print k[2] # output is 3

2. Slicing:
▪ A slice of a list is sub-list.
▪ Slicing using to access range of elements.
▪ This operation using two indices, separated by colon(:).
▪ First index is the starting point to extraction starts and second index is the
last point to be stop.
Example
Print k[2:5] #output is 3,4,5

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 1


LIST, DICTIONARY, TUPLE & SET Chapter 3

3. Joining two list:


▪ Concatenate two lists together.
▪ The plus(+) operator used to concatenate two list

Example
a= [1,2,3]
b=[4,5]
c=a+b
print c # it produce [1,2,3,4,5]

4. Repeating list:
▪ Multiplying a list by an integer n creates a new list that repeats the original
list n times.
▪ The operator * is used to repeating the list by n times.
Example
a=[1,2,3]
print (a*3) # It produce [1,2,3,1,2,3,1,2,3]
------------------------------------------
List functions and methods:
1. len(): It is used to get the length of a list.

Example:
k=[]
for i in range(0,3):
el=input("enter value")
k.append(el)
print(k)

print(len(k))

2. append(): To add an item to the end of a list.

Example
k=[]
for i in range(0,3):
el=input("enter value")
k.append(el)
print(k)

3. insert(): To insert a new element at the specified location.

Example
k=[]
for i in range(0,3):
el=input("enter value")

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 2


LIST, DICTIONARY, TUPLE & SET Chapter 3

k.append(el)
print(k)

k.insert(5,30)
print(k)

4. remove(value):
To remove the first occurrence of the specified element from the list.

Example
k=[]
for i in range(0,3):
el=input("enter value")
k.append(el)
print(k)

k.remove(20)
print(k)
5. sort(): This function used to sort/arrange the list item.

Example
k=[]
for i in range(0,3):
el=input("enter value")
k.append(el)
print(k)

k.sort()
print(k)

6. reverse(): This function reverse the list elements.

Example
k=[]
for i in range(0,3):
el=input("enter value")
k.append(el)
print(k)

print(k.reverse())

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 3


LIST, DICTIONARY, TUPLE & SET Chapter 3

7. count(value): To find the number of times a value occurs in a list.


8. extend(): To add the items in one list to an existing another list.
9. pop(): To returns and remove the rightmost element from the list.

IMPLEMENTATION OF STACK USING LIST:


Stack is a linear collection of data elements, where insertion and deletion
takes place at only one end called top; it works under the manner of LIFO [Last
In First Out].
Example Program to illustrate implementation of stack using list:
stack = []
def Push():
print("Enter element to Push:")
ele = input()
stack.append(ele)
def Pop():
if len(stack) == 0:
print("Stack is underflow")
else:
print("Popped element =", stack.pop())
def Display():
if len(stack) == 0:
print("Stack is underflow")
else:
print(stack, ":top")

while (1):
print("1. Push\n2. Pop\n3. Display\n4. Exit")
n = int(input("Enter your choice: "))
if n == 1:
Push()
elif n == 2:
Pop()
elif n == 3:
Display()
elif n == 4:

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 4


LIST, DICTIONARY, TUPLE & SET Chapter 3

break
else:
print("Invalid input")

IMPLEMENTATION OF STACK USING LIST:


Queue is a linear collection of data elements, where insertion takes place
at rear end and deletion takes place at front end, it works under the manner of
FIFO[First In First Out].
Example Program to illustrate implementation of queue using list:
queue = []
queue.append('a')
queue.append('b')
queue.append('c')
print("Initial queue")
print(queue)
print("\nElements dequeued from queue")
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))
print("\nQueue after removing elements")
print(queue)

NESTED LIST:
A list contains another list is called nested list.
Example:
L=[10,11,[100,200],[1000,2000,[111,222],12,13]
print(L)
print(list[3][3][0]) // print 111 value based on index value

------------------------------------------------------------------------------
DICTIONARY
▪ A dictionary is an unordered collection, changeable and indexed.
▪ In Python dictionaries are written with curly brackets, and they have keys
and values.
▪ That means dictionary contains pair of elements such that first element
represents the key and the next one becomes its value.
▪ The key and value should be separated by a colon (:) and every pair should
be separated by comma.
▪ All the elements should be enclosed inside curly brackets.

Characteristics of a Dictionary:
▪ A dictionary is an unordered collection of objects.
▪ Values are accessed using a key

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 5


LIST, DICTIONARY, TUPLE & SET Chapter 3

▪ A dictionary can shrink or grow as needed


▪ The contents of dictionaries can be modified.
▪ Dictionaries can be nested.
▪ Sequence operations, such as slice cannot be used with dictionary

Creating Python Dictionary


▪ Creating a dictionary is as simple as placing items inside curly
braces {} separated by commas.
▪ An item has a key and a corresponding value that is expressed as a pair
(key: value).

Example
my_dict = {} # empty dictionary

my_dict = {1: 'apple', 2: 'ball'} # dictionary with integer keys

my_dict = {'name': 'aaa', 1: [2, 4, 3]} # dictionary with mixed keys

OUTPUT:
{}
{1: 'apple', 2: 'ball'}
{'name': 'John', 1: [2, 4, 3]}

Accessing Elements from Dictionary


▪ While indexing is used with other data types to access values, a dictionary
uses keys.
▪ Keys can be used either inside square brackets [] or with
the get() method.

Example
my_dict = {'name': 'aaa', 'age': 26}
print(my_dict['name'])
print(my_dict.get('age'))

OUTPUT:
Jack
26

Operations or functions/methods in Dictionary:


1. clear()
2. copy()
3. get()
4. pop()
5. keys()
6. values()
7. items()
8. sorted()

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 6


LIST, DICTIONARY, TUPLE & SET Chapter 3

1. clear():
▪ It removes all the items from the dictionary.
▪ The clear() method removes all items from the dictionary.

Example
d = {1: "one", 2: "two"}
d.clear()
print('d =', d)

Output
d = {}

2. copy()
They copy() method returns a shallow copy of the dictionary.

Example
original = {1:'one', 2:'two'}
new = original.copy()
print('Orignal: ', original)
print('New: ', new)
Output
Orignal: {1: 'one', 2: 'two'}
New: {1: 'one', 2: 'two'}

3. get()
▪ It returns the value from a dictionary associated with the name.
▪ The get() method returns the value for the specified key if key is in
dictionary.

Example
person = {'name': 'Phill', 'age': 22}
print('Name: ', person.get('name'))
print('Age: ', person.get('age'))
print('Salary: ', person.get('salary'))
print('Salary: ', person.get('salary', 0.0))

Output
Name: Phill
Age: 22
Salary: None
Salary: 0.0

4. pop():
It remove the last item in the dictionary.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 7


LIST, DICTIONARY, TUPLE & SET Chapter 3

Example
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print(squares.pop(4))

5. keys()
▪ It returns list of all the keys used in the dictionary, in arbitrary order.
▪ The keys() method returns a view object that displays a list of all the keys
in the dictionary

Example
person = {'name': 'Phill', 'age': 22, 'salary': 3500.0}
print(person.keys())
empty_dict = {}
print(empty_dict.keys())

Output
dict_keys(['name', 'salary', 'age'])
dict_keys([])

6. values()
▪ It returns list of all values used in the dictionary.
▪ The values() method returns a view object that displays a list of all the
values in the dictionary.

Example
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
print(sales.values())

Output
dict_values([2, 4, 3])

7. items()
▪ It returns list of tuple(key : value) used in the dictionary.
▪ The items() method returns a view object that displays a list of dictionary's
(key, value) tuple pairs.

Example
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
print(sales.items())

Output
dict_items([('apple', 2), ('orange', 3), ('grapes', 4)])

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 8


LIST, DICTIONARY, TUPLE & SET Chapter 3

8. sorted()
▪ The sorted() method returns a sorted dictionary elements.

Example
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
print(sorted(sales))
Output
dict_items([('apple', 2), ('grapes', 4), ('orange', 3)])

Program to demonstrate use of Dictionaries:


Dict={6:60,7:70,1:10,2:20,3:30,4:40,5:50}
print(“dictionary elements are : “,Dict)
print(“length of the dictionary=”, len(Dict)
Dict.update({1:5})
print(“after updating dictionary elements are =”,Dict)
dict2=Dict.copy()
print(“After copy of dictionary, the dictionary 2 elements are:”,dist2)
Dict.pop(3)
print(“After removing an element = “,Dict)
print(“After sorted dictionary elements=”sorted(dict))
Dict.clear()
print(“After clearing elements from dictionary:,Dict)
----------------------------------------------------------------------------------------

TUPLE
▪ A tuple is similar to list.
▪ A tuple contains group of elements which can be different types.
▪ These elements in the tuple are separated by commas and enclosed in
parentheses ().
▪ Tuple are immutable.
▪ Tuples once created cannot be modified.
▪ The tuple cannot change dynamically. That means a tuple can be treated
as read-only list.

Creation of tuple:
Tuple can be created by using Square braces or flower braces and
separated by comma operator.
Tuple_name [ele1,ele2,ele3,…]
Or
Tuple_name={ele1,ele2,ele3,…}

Operation or Built – in function / Methods of tuple


1] len():
This function is used to find the number of elements in the tuple

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 9


LIST, DICTIONARY, TUPLE & SET Chapter 3

n=len(tuple)

2] count() :
This method is used to find the no of times a given element present in the
tuple.
m= tuple.count(20)

3] max() :
This method is used to find the Maximum element in the tuple.
large= Max(tuple)

4] min() :
This method is used to find the minimum element in the tuple.
Small = min(tuple)
tuple=(10,20,30,40,50,20)

Example program to illustrate tuple methods


n=len(tuple)
print(“Length of tuple = “,n)
m=tuple.count(20)
print(“No of times 20 present in tuple = “,m)
print(“Maximum element = ”,max(tuple))
print(“Minimum of element = “,min(tuple))

Output :
Length of tuple = 6
No of times 20 present in tuple =2
Maximum element =50
Minimum element=10
------------------------------------------------------------------------------------
SET
▪ A set is an unordered collection of items.
▪ Every set element is unique (no duplicates) and must be immutable (cannot
be changed).
▪ However, a set itself is mutable. We can add or remove items from it.
▪ Sets can also be used to perform mathematical set operations like union,
intersection, symmetric difference, etc.

Creating Python Sets


A set is created by placing all the items (elements) inside curly braces {},
separated by comma, or by using the built-in set() function.

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 10


LIST, DICTIONARY, TUPLE & SET Chapter 3

# Different types of sets in Python

# set of integers
my_set = {1, 2, 3}
print(my_set)

# set of mixed datatypes


my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)

Output
{1, 2, 3}
{1.0, (1, 2, 3), 'Hello'}

Set Operations

Set Operations
Python provides the methods for performing set union, intersection,
difference, and symmetric difference operations.
Example:
s1 = {1, 4, 5, 6}
s2 = {1, 3, 6, 7}
print(s1.union(s2))
print(s1 | s2)
print(s1.intersection(s2))
print(s1 & s2)
print(s1.difference(s2))
print(s1 - s2)
print(s1.symmetric_difference(s2))
print(s1 ^ s2)

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 11


LIST, DICTIONARY, TUPLE & SET Chapter 3

Operations or Built in functions / Methods of Sets:


1] len() :
This function is used to find the number of elements in the sets.
n= len(sets)
2] max() :
This method is used to find the Maximum elements in the sets .
large=max(sets)
3] min() :
This method is used to find the Minimum elements in the sets.
Small=min(sets)
4] add() :
This method is used to add new element into the sets.
sets.add(60)
5] discard() :
This method is used to remove particular element from the sets.
sets.discard(50)

Example program to illustrate set methods


sets={10,20,30,40,50,20}
n=len(sets)
print(“length of set = “,n)
print(“Maximum element = “,max(sets))
print(“Minimum element = “,min(sets))
sets.add(60)
print(sets)
sets.discard(50)
print(sets)
---------------------------------------------------------------------------------

Difference between list and tuple


LIST TUPLE
List are enclosed in square brackets [] Tuple are enclosed in parentheses ()
Element and size can be changed Can’t be changed.
Is a mutable object Is a Immutable object
It can grow and shrink as needed It is read only list

JANHAVI N L, Asst. Prof., Dept. of BCA, VVFGC, Tumkur 12

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy