0% found this document useful (0 votes)
26 views55 pages

Unit 3 - Lists - Tuples - Sets

The document provides an overview of Python's collection data types, including lists, tuples, sets, and dictionaries, detailing their characteristics and usage. It explains how to create, modify, and access elements within these collections, along with built-in functions and methods applicable to them. Additionally, it covers advanced topics like nested lists and deques, highlighting their operations and differences from standard lists.
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)
26 views55 pages

Unit 3 - Lists - Tuples - Sets

The document provides an overview of Python's collection data types, including lists, tuples, sets, and dictionaries, detailing their characteristics and usage. It explains how to create, modify, and access elements within these collections, along with built-in functions and methods applicable to them. Additionally, it covers advanced topics like nested lists and deques, highlighting their operations and differences from standard lists.
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/ 55

UNIT 3 - LISTS , DICTIONARY, TUPLES,

SETS
Reference textbook :
An introduction to Python programming
Author: Gowrishankar S

Python Unit 3 - GSS BCA : Prof Shweta Dalvi


Python Collections
• 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, unchangeable*,
and unindexed. No duplicate members.
– Dictionary is a collection which is ordered** and
changeable. No duplicate members.
Python Unit 3 - GSS BCA : Prof Shweta Dalvi
1. Lists
definition and creating lists
• A list is a data structure (or built in datatype) and an
ordered set of values, where each value is identified
by an index.
• The values that make up a list are called its elements
or items.
• List items are ordered, changeable (mutable) , and
allow duplicate values.
• List items are indexed, the first item has index [0],
the second item has index [1] etc.

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
creating lists:
• Lists are constructed using square brackets [ ]
wherein you can include a list of items
separated by commas.
• example:
shopping_list = [“biscuits”, “bread”, “fruits”, “tea” ]
num_list = [12, 7, 13, 22]
mix_list = [12, “hello”, 13.5 ]
empty_list = [ ]

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
Creating lists using list() constructor or method:
Syntax is : list([sequence])
where the sequence can be a string, tuple or
list itself.
Example:
mylist=list(“ python“)
mylist= list((“biscuits”, “bread”, “milk”))
mylist = list([ 2, 4, 6])
Python Unit 3 - GSS BCA : Prof Shweta
Dalvi
Printing a list : List can be printed simply by
specifying its name in print method.
Example:
print(shopping_list) # [“biscuits”, “bread”, “fruits”, “tea” ]

print(num_list) # [12, 7, 13, 22]

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
Basic list operations
• lists can also be concatenated using the +
sign, and the * operator is used to
create a repeated sequence of list items.
Example:
list_1 = [1, 3, 5, 7]
list_2 = [2, 4, 6, 8]
list_1 + list_2 # [1, 3, 5, 7, 2, 4, 6, 8]
list_1 * 3 # [1, 3, 5, 7, 1, 3, 5, 7, 1, 3, 5, 7]
list_1 == list_2 # False
Python Unit 3 - GSS BCA : Prof Shweta
Dalvi
Accessing list items
• Using square brackets [ ] we can access individual list
items wherein ,the first item is at index 0, the second
item is at index 1 and so on. The index provided within
the square brackets indicates the value being accessed.
• example:
shopping_list = [“biscuits”, “bread”, “fruits”, “tea” ]
shopping_list[0] # biscuits
shopping_list[1] # bread
shopping_list[2] # fruits
shopping_list[3] # tea

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
• We can also access items from the list with a
negative index number, by counting backwards
from the end of the list, starDng at −1.
• example:
shopping_list = [“biscuits”, “bread”, “fruits”, “tea” ]
shopping_list[-1] # tea
shopping_list[-2] # fruits
shopping_list[-3] # bread
shopping_list[-4] # biscuits
Python Unit 3 - GSS BCA : Prof Shweta
Dalvi
Accessing list items using Range of Indexes
• We 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 list with the specified items.
• Example
shopping_list = [“biscuits”, “bread”, “fruits”, “tea” ]
print(shopping_list[1:3] ) # [bread, fruits]
print(shopping_list[1:]) # [bread, fruits,tea]
print(shopping_list[:2] ) # [biscuits, bread]
Python Unit 3 - GSS BCA : Prof Shweta
Dalvi
Modifying items in list
• Lists are mutable in nature as the list items can be
modified after we have created a list.
• example:
in below shopping_list we can modify the item bread
to sweet bread and tea to green tea
shopping_list = [“biscuits”, “bread”, “fruits”, “tea” ]
shopping_list[1] = “ sweet bread”
shopping_list[-1] = “ green tea”

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
• Using an assignment (=) operator on lists
does not make a new copy. Instead, assignment
makes both the variable names point to the same list
in memory.
zoo = ["Lion", "Tiger", "Zebra"]
forest = zoo
print(zoo is forest) #True

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
Copying a list using copy () method:
example:
thislist = [“books", “pen", “pencil"]
mylist = thislist.copy() #creates a copy of thislist
print(mylist)
print(thislist)
print(mylist is thislist) #false
nwlist=thislist #nwlist only references thislist
print(nwlist is thislist) #true

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
• Slicing of lists (extracting a part of the list ) can be done by
specifying list name and index range along with the colon (:)
operator.
• Syntax is : list_name [ start : stop [:step]]
• example:
fruits = ["grapefruit", "pineapple", "blueberries", "mango",
"banana"]

fruits[1:3] #output is ['pineapple', 'blueberries']

fruits[:3] #output is ['grapefruit', 'pineapple', 'blueberries']

fruits[2:] # output is ['blueberries', 'mango', 'banana']

fruits[1:4:2] # output is ['pineapple', 'mango']


Python Unit 3 - GSS BCA : Prof Shweta
Dalvi
fruits[:] #output is ['grapefruit', 'pineapple',
'blueberries', 'mango', 'banana']

fruits[::2] #output is ['grapefruit', 'blueberries',


'banana']

fruits[::-1] #output is ['banana', 'mango',


'blueberries', 'pineapple', 'grapefruit']

fruits[-3:-1] #output is ['blueberries', 'mango']

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
Dynamically building a list or populating a list

#creating and populating a list dynamically


items_of_list = []
total_items = int(input("Enter the number of items "))
for i in range(total_items):
item = input("Enter list item: ")
items_of_list.append(item)
print(f"List items are {items_of_list}")

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
#traversing (going through) each list item
food_list = ["waffles", "sandwich","fries"]
beverage_list = ["mojito", "tea", "cold coffee"]

#method 1 traversing using list name


for x in food_list:
print(f"I like to eat {x}")

#method 2 traversing using list itself


for y in ["mojito", "tea", "cold coffee"]:
print(f"I like to drink {y}")
Python Unit 3 - GSS BCA : Prof Shweta
Dalvi
Built in functions Description

len() The len() function returns the numbers of


items in a list.

sum() The sum() function returns the sum of


numbers in the list.

any() The any() function returns True if any of


the Boolean values in the list is True.

all() The all() function returns True if all the


Boolean values in the list are True, else
returns False.

sorted() The sorted() function returns a modified


copy of the list while leaving the original
list
untouched.

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
Method Description Syntax

append() Adds an element at the end of the list list.append(item)

clear() Removes all the elements from the list.clear()


list
copy() Returns a copy of the list x = list.copy()

count() Returns the number of elements with list.count(item)


the specified value

extend() Add the elements of a list 2, to the list.extend(list2)


end of the current list

index() Returns the index of the first element list.index(item)


with the specified value

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
Method Description Syntax

insert() Adds an element at the specified list.insert(index, item)


position

pop() Removes the element at the list.pop([index])


specified position

remove() Removes the first item with the list.remove(item)


specified value

reverse() Reverses the order of the list list.reverse()

sort() Sorts the list list.sort()

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
Deque
(Doubly Ended Queue)

• Deque is a container that belongs to Collections module of


python
• It provides quicker append and pop operations from both
sides of the container compared to list.
• It provides O(1) time complexity for append and pop
operations as compared to list which has O(n) time
complexity.

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
Operations on deque

• append():- This function is used to insert the


value in its argument to the right end of the
deque.
• appendleft():- This function is used to insert the
value in its argument to the left end of the deque.
• pop():- This function is used to delete an
argument from the right end of the deque.
• popleft():- This function is used to delete an
argument from the left end of the deque.
• len(dequeue):- Return the current size of the
dequeue.
Python Unit 3 - GSS BCA : Prof Shweta
Dalvi
Nested Lists
• A list inside another list is called a nested list and we can
use for loop to traverse through it.
• Nested lists look similar to matrix
• Example:
asia = [ ["India", "Japan", "Korea"] ,
["Srilanka", "Myanmar", "Thailand"] ,
["Cambodia", "Vietnam", "Israel"] ]
• To access the items
asia[0] # ['India', 'Japan', 'Korea']
asia[0][1] # 'Japan'
asia[1][2] # “Thailand"
asia #[['India', 'Japan', 'Korea'], ['Srilanka',
'Myanmar', ‘Thailand'], ['Cambodia',
'Vietnam', 'Israel']
Python Unit 3 - GSS BCA : Prof Shweta
Dalvi
DEL
• Del is used to remove an item from a list based on its
index and also to clear a list.
• Del does not return any value
#to demonstrate use of del
a = [5, -8, 99.99, 432, 108, 213]
print("Initial list is",a)
del a[0]
print(" after deleting a[0]" , a)
del a[2:4]
print(" after deleting a[2] to a[4]" ,a)
del a[:]
print(" after deleting entire list" ,a)
Python Unit 3 - GSS BCA : Prof Shweta
Dalvi
2. DICTIONARIES

• A dictionary is a collection of an ordered, mutable set


of key : value pairs, wherein the keys are unique and
hence don’t allow duplicates.
• Before 3.7 version of python dictionaries were
unordered.
• Dictionaries are constructed using curly braces
{ }, wherein you include a list of key : value pairs
separated by commas.
• Dictionaries are indexed by keys
• Dictionary keys are case sensitive.

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
• Syntax to create dictionary:
dictionary_name = { key_1 : value_1 ,
key_2:value_2 ,
key_3:value_3 ,
………,key_n:value_n }
Example:
fish = {"g": "goldfish", "s":"shark",
"n": "needlefish", "b":"barramundi",
"m":"mackerel“ }
print(fish)

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
Python Unit 3 - GSS BCA : Prof Shweta
Dalvi
Keys in dictionary
• Dictionary is mutable but their keys are
immutable type
• Keys can be either a string or a number.
• Since lists are mutable, we cannot use lists as
keys.
• Duplicate keys are not allowed in the dictionary.
• the output of dictionary is ordered key:value
pairs i.e. The order in which we inserted items
into the dictionary

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
• Dictionary items can be of any type including string,
numbers, boolean, list
mixed_dict = {"portable“ : "laptop",
9 : 11,
"colors“ : ["red", "white", "blue"] ,
7 : "julius“,
"electric“ : False,
"year“ : 1964 }
print ( mixed_dict)
type(mixed_dict)
empty_dict = { }
print(empty_dict)

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
Creating dictionary using dict() constructor
• It is also possible to use the dict() constructor to make
a dictionary. Syntax: dict ( [**kwargs] )
• If no keyword argument is given, an empty dictionary
is created.
• If keyword arguments are given, the keyword
arguments and their values (kwarg = value) are added
to the dictionary as key:value pairs.
• example:
thisdict = dict(name = “Rohan",
age = 36,
country = “India")
print(thisdict)

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
Accessing and modifying dictionary
• Each individual key:value pair in a dictionary can be
accessed through keys by specifying it inside square
brackets.
dictionary_name[key]
• The syntax for modifying the value of an existing key
or for adding a new key:value pair to a dictionary is,
dictionary_name[key] = value
If the key is already present in the dictionary, then
the key gets updated with the new value. If the key is
not present then the new key:value pair gets added
to the dictionary.
Python Unit 3 - GSS BCA : Prof Shweta
Dalvi
built-in functions for which a dictionary can be
passed as an argument

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
Python Unit 3 - GSS BCA : Prof Shweta
Dalvi
Python Unit 3 - GSS BCA : Prof Shweta
Dalvi
Populating dictionary with key : value
pairs
• To populate a dictionary start with an empty
dictionary { }, then use the update() method to assign a
value to the key using assignment operator.
• If the key does not exist, then the key:value pairs will
be created automatically and added to the dictionary.
• Example:
countries = { }
countries.update( { Asia : India})
countries.update( { Europe : Germany})
countries.update( { Australia : NewZealand})
print(countries)

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
Building dictionary dynamically from
user input
• method 1: We can use the for loop to read
and build a dictionary.
• method 2: can use the dictionary_name[key]
= value format to add key:value pairs to the
dictionary
• method 3: We can use the while loop to read
and build a dictionary

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
Traversing dictionary
• A for loop can be used to iterate over keys or
values or key:value pairs in dictionaries.
• by default, it will iterate over the keys.
• If we want to iterate over the values, we have
to use values() method and for iterating over
the key:value pairs, use items() method.

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
Using DEL to remove a key value pair from dicitonary

• To delete the key:value pair, use the del statement


followed by the name of the dictionary along with
the key you want to delete.
• Syntax: del dict_name[key]
• Example:
animals = {"r":"raccoon", "c":"cougar", "m":"moose"}
print(animals)
del animals[r]
print(animals)
Python Unit 3 - GSS BCA : Prof Shweta
Dalvi
3. TUPLES
• A tuple is defined as a data structure that
contains an ordered, finite sequence of
immutable, heterogeneous elements that are
of fixed sizes.
• Tuples can return more than one value from
a function
• Tuples can also be used to pass multiple
values through one function parameter.

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
Creating tuples:
• A tuple is defined by putting a comma-separated list of
values inside parentheses ( ). Each value inside a tuple is
called an item.
• Syntax:
tuple_name = (item_1, item_2, item_3, ..., item_n)
• We can have a mix of different types of items in tuples, and
they need not be homogeneous.
• Example:
internet = ("cern", "tim bernerslee", "www", 1980)
print(internet)
type(internet)

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
• Some more examples of tuples:
newtuple = "ferrari", "redbull", "mercedes“
print(newtuple)
empty_tuple = ()
print( empty_tuple)
air_force = ("f15", "f22a", "f35a")
fighter_jets = (1988, 2005, 2016, air_force)
print(fighter_jets)

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
Creating tuple using tuple() function
Syntax: tuple([sequence])
where the sequence can be a number, string or tuple itself .
Example:
college=“gssbca”
tp = tuple(college)
print( tp)
letters = ("a", "b", "c")
numbers = (1, 2, 3)
nested_tuples = (letters, numbers)
print(nested_tuples )

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
Basic tuple operations
• the + operator is used to concatenate tuples together
and the * operator to repeat a sequence of tuple items.
• Example:
tuple_1 = (2, 0, 1, 4)
tuple_2 = (2, 0, 1, 9)
print(tuple_1 + tuple_2) #(2, 0, 1, 4, 2, 0, 1, 9)
print(tuple_1 * 3 ) #(2, 0, 1, 4, 2, 0, 1, 4, 2, 0, 1, 4)
print(tuple_1 == tuple_2) #False
print( 2 in tuple_1) #True
print(5 in tuple_1) #False
print(tuple_1 > tuple_2) #False
Python Unit 3 - GSS BCA : Prof Shweta
Dalvi
Indexing and slicing in tuples
Indexing in tuples:
• Each item in a tuple can be accessed individually
by using the square brackets .
• Syntax: tuple_name[index]
where is an integer value and indicates the item
to be selected.
• example: air_force = ("f15", "f22a", "f35a")
print(air_force[0]) #f15
print(air_force[2]) #f35a
print(air_force[ -2]) #f22a

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
• Slicing in tuples: It allows a part of the tuple to be
extracted by specifying an index range along with the
colon (:) operator.
• Syntax: tuple_name[start:stop[:step]]
• Example:
colors = ("v", "i", "b", "g", "y", "o", "r")
print(colors) #('v', 'i', 'b', 'g', 'y', 'o', 'r')
print ( colors[ 2 : 5 ]) # ('b', 'g', 'y')
print ( colors[ : 5 ]) #('v', 'i', 'b', 'g', 'y')
print ( colors[3 : ]) #('g', 'y', 'o', 'r')
print ( colors[ : ]) #('v', 'i', 'b', 'g', 'y', 'o', 'r')
print(colors[::]) #('v', 'i', 'b', 'g', 'y', 'o', 'r')
print( colors[1:5:2] ) # ('i', 'g')
print(colors[-5:-2] ) # ('b', 'g', 'y')
Python Unit 3 - GSS BCA : Prof Shweta
Dalvi
str = (‘g’, ‘s’, ‘s’, ‘b’, ‘c’, ‘a’ )
Str[ 2: 3]
Str[ 3: ]
Str[ : 2]
Str[ -3 ]

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
Builtin functions used on tuples

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
Tuple methods
method syntax description

The count() method


count() tuple_name.count(item) counts the number of
times the item appears
in the tuple

index() tuple_name.index(item) The index() method


searches for the given
or item from the start of
the tuple and returns its
tuple_name.index(item, start, index
end)
. If the item is not
present in the tuple,
then ValueError is
thrown by this method.
Python Unit 3 - GSS BCA : Prof Shweta
Dalvi
Tuple Packing and Unpacking
• It is possible to assign multiple value to an single
object and pack them together into a tuple . This is
called as tuple packing.
• Example:
t = 123, 456, ‘hello’
• Also, it is possible to assign a single value to multiple
objects or variables at once. This is called as tuple
unpacking
• Example:
x,y=t
x, y = t, p

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
#swapping of two numbers without using temporary variables
def main():
a = int(input("Enter a value for first number "))
b = int(input("Enter a value for second number "))
b, a = a, b
print("After Swapping")
print(f"Value for first number {a}")
print(f"Value for second number {b}")
if __name__ == "__main__":
main()
Python Unit 3 - GSS BCA : Prof Shweta
Dalvi
4. SETS
• A set is an unordered collection with no duplicate
items.
• Set items are not indexed and therefore each time we
access the index , we can find different value.
• Sets are used for membership testing , eliminating
duplicate entries, performing mathematical operations,
such as union, intersection, difference, and symmetric
difference.
• Curly braces { } or the set() function can be used to
create sets with a comma-separated list of items.
• Example : books = {“python”,” dbms”, “c# “}
• Note: to create an empty set you have to use set()

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
creating sets and accessing items :

basket={"cookies","pastry" ,"cake","muffins","cake"}
print(basket) # {'cookies',' pastry' , 'cake ', 'muffins‘}
for x in basket
print(“ set elememt is “, x)

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
Set Methods

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi
Python Unit 3 - GSS BCA : Prof Shweta
Dalvi
Frozenset
• A frozenset is basically the same as a set,
except that it is immutable.
• Once a frozenset is created, then its items
cannot be changed.
• Since they are immutable, they can be used as
members in other sets and as dictionary keys

Python Unit 3 - GSS BCA : Prof Shweta


Dalvi

You might also like