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

UNIT3 Python

Notes

Uploaded by

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

UNIT3 Python

Notes

Uploaded by

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

UNIT:3

Lists, Tuples, Sets, and Dictionaries


List
Lists are used to store different data items in a single variable.

A list can be defined as a collection of values or items of different types. Python lists
are mutable type which implies that we may modify its element after it has been
formed. The items in the list are separated with the comma (,) and enclosed with the
square brackets [].

Lists are one of 4 built-in data types in Python used to store collections of data, the
other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.

List Declaration

# A simple list
list1 = [1, 2, "Python", "Program", 15.9]

list2 = ["apple", "banana", "mango", "grapes"]

print(list1)
print(list2)

print(type(list1))

Output:
[1, 2, 'Python', 'Program', 15.9]

['apple', ‘banana’, 'mango', ‘grapes’]

< class ' list ' >

Characteristics of Lists
The list has the following characteristics:

o The lists are ordered. it means that the items have a defined order, and that order
will not change.
o The element of the list can access by index.
o The lists are the mutable type (Changeable). The list is changeable, meaning that
we can change, add, and remove items in a list after it has been created.
o A list can store the number of various elements.
o Allows duplicate values

Operations on List in python


• Access Items
• Check if Item Exists
• Change Item Value
• Insert Items
• Append Items
• Add Any Iterable
• Remove Specified Item
• Remove Specified Index
• Clear the List
• Sort the list
• Copy the list
• Join the lists

1.Access Items in list

List items are indexed and you can access them by referring to the index number:

Example:

List1= ["apple", "banana", "cherry"]


print(List1[1])
output:
banana
Negative Indexing

Negative indexing means start from the end

-1 refers to the last item, -2 refers to the second last item etc.

Example:

List1= ["apple", "banana", "cherry"]


print(List1[-1])
output:
cherry

Range of Indexes

You can specify a range of indexes by specifying where to start and where to end the
range.

When specifying a range, the return value will be a new list with the specified items.

Example:

Return the third, fourth, and fifth item:

List1 = ["apple", "banana", "cherry", "orange", "kiwi", "watermelon", "mango"]


print(List1[3:6])
output:
orange
kiwi
watermelon

2.Check if Item Exists


To determine if a specified item is present in a list use the in keyword:
Example:
List1 = ["apple", "banana", "cherry"]
if "apple" in List1:
print("Yes, 'apple' is in the fruits list")

output:

Yes, 'apple' is in the fruits list

3.Change Item Value


To change the value of a specific item, refer to the index number:
Example:
List1 = ["apple", "banana", "cherry"]
List1[0]=(“mango”)
Print(list1)

Output:

["mango", "banana", "cherry"]


4.Insert Items
To insert a new list item, without replacing any of the existing values, we can use
the insert() method.

The insert() method inserts an item at the specified index:

Example:

List1 = ["apple", "banana", "cherry"]


List1.insert(2,”grapes”)
Print(list1)

Output:
["apple", "banana”, “grapes”, "cherry"]

5.Append Items
To add an item to the end of the list, use the append() method:

List1 = ["apple", "banana", "cherry"]


List1.append(“mango”)
Print(list1)

Output:
["apple", "banana”, "cherry”, “mango”]

6.Add Any Iterable


The extend() method does not have to append lists, you can add any iterable object
(tuples, sets, dictionaries etc.).

List1 = ["apple", "banana", "cherry"]


Tuple1 = ("kiwi", "orange")
List1.extend(Tuple1)
print(List1)

Output:
["apple", "banana”, "cherry”, “kiwi”, “orange”]

7.Remove Specified Item


The remove() method removes the specified item.
List1 = ["apple", "banana", "cherry"]
List1.remove("banana")
print(List1)

Output:
["apple", "cherry”]

8.Remove Specified Index


The pop() method removes the specified index.

Example

Remove the second item:

List1 = ["apple", "banana", "cherry"]


List1.pop(0)
print(List1)

Output:
["banana", "cherry”]

If you do not specify the index, the pop() method removes the last item.

Example

Remove the last item:

List1 = ["apple", "banana", "cherry"]


List1.pop()
print(List1)

Output:
[“apple”, "banana"]

The del keyword can also delete the list completely.

Example

Delete the entire list:

List1 = ["apple", "banana", "cherry"]


del List1

9.Clear the List


The clear() method empties the list.

The list still remains, but it has no content.


Example

Clear the list content:

List1 = ["apple", "banana", "cherry"]


List1.clear()
print(List1)

Output:
[]

10.Sort the lists

Sort List Alphanumerically


List objects have a sort() method that will sort the list alphanumerically, ascending,
by default:

Example:

Sort the list alphabetically:

List1 = ["orange", "mango", "kiwi", "pineapple", "banana"]


List1.sort()
print(List1)

Output:

["banana", "kiwi", "mango”, “orange", "pineapple"]

Example:

Sort the list numerically:

List1 = [99, 50, 65, 82, 23]


List1.sort()
print(List1)

Output:

[23,50,65,82,99]

Sort Descending

To sort descending, use the keyword argument reverse = True:


Example

Sort the list descending:

List1 = ["orange", "mango", "kiwi", "pineapple", "banana"]


List1.sort(reverse = True)
print(List1)

Output:

["pineapple”, “orange", "mango”, "kiwi", “banana"]

Example

Sort the list descending:

List1 = [100, 50, 65, 82, 23]


List1.sort(reverse = True)
print(List1)

Output:

[100,82,65,50,23]

11.Copy a List
There are ways to make a copy, one way is to use the built-in List method copy().

Example

Make a copy of a list with the copy() method:

List1 = ["apple", "banana", "cherry"]


List2 = List1.copy()
print(List2)

Output:

["apple", "banana", "cherry"]

12.Join Two Lists


There are several ways to join, or concatenate, two or more lists in Python.

One of the easiest ways are by using the + operator.


Example

Join two list:

list1 = ["a", "b", "c"]


list2 = [1, 2, 3]

list3 = list1 + list2


print(list3)

output:

["a", "b", "c",1, 2, 3]

Loop Through a List


You can loop through the list items by using a for loop:

Example:

Print all items in the list, one by one:

List1 = ["apple", "banana", "cherry"]


for x in List1:
print(x)

Output:

apple
banana
cherry
List Methods
Python has a set of built-in methods that you can use on lists.

Method Description

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

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the item with the specified value


reverse() Reverses the order of the list

sort() Sorts the list

Nested lists

A list within another list is referred to as a nested list in Python

Example:

Nested_List1 = [2, 3, 4, [10,20,30], 78, 23]

Print(Nested_List1)

Output:

[2, 3, 4, [10,20,30], 78, 23]

Accessing the element in a nested list

Print(Nested_List1[3][1])

Output:

20

Print(Nested_List1[3])

Output:

[10,20,30]
Implementation of stack using list
A stack is a linear data structure that stores items in a Last-In/First-Out
(LIFO) or First-In/Last-Out (FILO) manner. In stack, a new element is added at
one end and an element is removed from the same end. The insert and
delete operations are often called push and pop.
push
pop
30
top of the stack
20
10

Implementation using list:

Python’s built-in data structure list can be used as a stack. Instead of push(),
append() is used to add elements to the top of the stack while pop() removes
the element in LIFO order.

# Python program to
# demonstrate stack implementation
# using list
stack = []

# append() function to push


# element in the stack
stack.append('a')
stack.append('b')
stack.append('c')
print('\nElements popped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())
print('\nStack after elements are popped:')
print(stack)

Output:

Initial stack
['a', 'b', 'c']
Elements popped from stack:
c
b
a

Stack after elements are popped:


[]

Implementation of queue using list


Like stack, queue is a linear data structure that stores items in First In First Out
(FIFO) manner. With a queue the least recently added item is removed first. A good
example of queue is any queue of consumers for a resource where the consumer
that came first is served first.

Elements can be inserted at one end called rear, elements can be deleted at
another end called front

2 4 6 7 8 10

Rear end front end

List is a Python’s built-in data structure that can be used as a queue. Instead of
rear() and front(), append() and pop() function is used.
# Python program to
# demonstrate queue implementation
# using list
# Initializing a queue
queue = []
# Adding elements to the queue
queue.append('a')
queue.append('b')
queue.append('c')
print("Initial queue")
print(queue)

# Removing elements from the queue


print("\nElements removed from queue")
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))

print("\nQueue after removing elements")


print(queue)

Output:

Initial queue
['a', 'b', 'c']

Elements dequeued from queue


a
b
c

Queue after removing elements


[]

Tuple
Tuples are used to store multiple items in a single variable.

A tuple is a collection which is ordered and unchangeable.

Example
Create a Tuple:

Tuple1 = ("apple", "banana", "cherry",10,20.5)


print(Tuple1)
Output:

("apple", "banana", "cherry",10,20.5)

Characteristics of tuple

Tuple Items

Tuple items are ordered, unchangeable, and allow duplicate values.

Tuple items are indexed, the first item has index [0], the second item has index [1] etc.

Ordered

When we say that tuples are ordered, it means that the items have a defined order, and
that order will not change.

Unchangeable

Tuples are unchangeable, meaning that we cannot change, add or remove items after
the tuple has been created.

Allow Duplicates

Since tuples are indexed, they can have items with the same value:

Example

Tuples allow duplicate values:

Tuple1 = ("apple", "banana", "cherry", "apple", "cherry")


print(Tuple1)

Output:

("apple", "banana", "cherry", "apple", "cherry")

Operations on tuple in python


• Finding length of tuple
• Access Items
• Check if Item Exists
• Join the two tuples
Tuple Length

To determine how many items a tuple has, use the len() function:

Example

Print the number of items in the tuple:

Tuple1 = ("apple", "banana", "cherry")


print(len(Tuple1))

Output:
3

2.Access Tuple Items


You can access tuple items by referring to the index number, inside square brackets:

Example

Print the second item in the tuple:

Tuple1= ("apple", "banana", "cherry")


print(Tuple1[1])

Output:
banana

Negative Indexing
Negative indexing means start from the end.

-1 refers to the last item, -2 refers to the second last item etc.

Example

Print the last item of the tuple:

Tuple1 = ("apple", "banana", "cherry")


print(Tuple1[-1])

Output:
cherry

3.Check if Item Exists


To determine if a specified item is present in a tuple use the in keyword:
Example

Check if "apple" is present in the tuple:

Tuple1 = ("apple", "banana", "cherry")


if "apple" in Tuple1:
print("Yes, 'apple' is in the fruits tuple")

Output

Yes, 'apple' is in the fruits tuple

4.Join Two Tuples


To join two or more tuples, you can use the + operator:

Example

Join two tuples:

tuple1 = ("a", "b" , "c")


tuple2 = (1, 2, 3)

tuple3 = tuple1 + tuple2


print(tuple3)

Output:

("a", "b" , "c",1, 2, 3)

Tuple Methods
Python has two built-in methods that you can use on tuples.

Method Description

count() Returns the number of times a specified value occurs in a


tuple
index() Searches the tuple for a specified value and returns the
position of where it was found

Count() method

Return the number of times the value 5 appears in the tuple:

Tuple1 = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)

x = Tuple1.count(5)

print(x)
Output:

index() method

Search for the first occurrence of the value 8, and return its position:

Tuple1 = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)

x = Tuple1.index(8)

print(x)

Output:
3
Sets in python
Sets are used to store multiple items in a single variable.

A set is a collection which is unordered, unchangeable*, and unindexed.

Sets are written with curly brackets.

Example

Create a Set:

Set1 = {"apple", "banana", "cherry"}


print(Set1)

Output:

{"apple", "banana", "cherry"}

Set Items

Set items are unordered, unchangeable, and do not allow duplicate values.

Unordered

Unordered means that the items in a set do not have a defined order.

Set items can appear in a different order every time you use them, and cannot be
referred to by index or key.

Unchangeable

Set items are unchangeable, meaning that we cannot change the items after the set
has been created. Once a set is created, you cannot change its items, but you can
remove items and add new items.

Duplicates Not Allowed

Sets cannot have two items with the same value.

Operations on sets in python


• Access Items
• Check if Item Exists
• add Items
• Add Any Iterable
• Remove Specified Item
• Clear the List
• Copy the list
• Join the lists

1.Access Items
You cannot access items in a set by referring to an index or a key.

But you can loop through the set items using a for loop, or ask if a specified value is
present in a set, by using the in keyword.

Set1 = {"apple", "banana", "cherry"}

for x in Set1:
print(x)

Output:

cherry
banana
apple

Check if "banana" is present in the set:

Set1 = {"apple", "banana", "cherry"}

print("banana" in Set1)

Output:
True

Add Items
Once a set is created, you cannot change its items, but you can add new items.
To add one item to a set use the add() method.

Example:

Add an item to a set, using the add() method:

Set1 = {"apple", "banana", "cherry"}


Set1.add("orange")
print(Set1)

Output: {"apple", "banana", "cherry”, “orange”}

Add Sets

To add items from another set into the current set, use the update() method.

Set1 = {"apple", "banana", "cherry"}


Set2 = {"pineapple", "mango", "papaya"}
Set1.update(Set2)
print(Set1)
Output:

{"apple", "banana", "mango", "cherry”, "pineapple", "papaya"}

4.Remove Item
To remove an item in a set, use the remove(), or the discard() method.

Example:

Remove "banana" by using the remove() method:

set1= {"apple", "banana", "cherry"}


set1.remove("banana")
print(set1)

Output:

{"apple", "cherry”}

You can also use the pop() method to remove an item, but this method will remove a
random item, so you cannot be sure what item that gets removed.

The return value of the pop() method is the removed item.


Clear the content of set
The clear() method empties the set:

set1 = {"apple", "banana", "cherry"}


set1.clear()
print(set1)

output:

set()

Join Two Sets


There are several ways to join two or more sets in Python.

You can use the union() method that returns a new set containing all items from both
sets, or the update() method that inserts all the items from one set into another:

Example:

The union() method returns a new set with all items from both sets:

set1 = {"a", "b", "c"}


set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)

output:

{"a", "b", "c",1,2,3}

Intersection of two sets


The intersection() method will return a new set, that only contains the items that are
present in both sets.

Example

Return a set that contains the items that exist in both set x, and set y:

x = {"apple", "banana", "cherry"}


y = {"kiwi", "mango", "apple"}

z = x.intersection(y)

print(z)
output:

{‘apple’}

Difference of two sets


The difference() method returns a set that contains the difference between two sets.

Meaning: The returned set contains items that exist only in the first set, and not in
both sets.

Syntax

set.difference(set)

Return a set that contains the items that only exist in set x, and not in set y:

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}
z = x.difference(y)
print(z)

output:

{“banana”,”cherry”}

Python has a set of built-in methods that you can use on sets.

Method Description

add() Adds an element to the set

clear() Removes all the elements from the set

copy() Returns a copy of the set


difference() Returns a set containing the difference
between two or more sets

discard() Remove the specified item

intersection() Returns a set, that is the intersection of


two or more sets

issubset() Returns whether another set contains


this set or not

issuperset() Returns whether this set contains


another set or not

pop() Removes an element from the set

remove() Removes the specified element

symmetric_difference() Returns a set with the symmetric


differences of two sets

union() Return a set containing the union of sets

update() Update the set with another set, or any


other iterable
Dictionaries in python
Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered*, changeable and do not allow


duplicates.

Dictionaries are written with curly brackets, and have keys and values:

d1={'name':'lavanya','class':'bca','regno':1001}
print(d1)

Output:

{'name': 'lavanya', 'class': 'bca', 'regno': 1001}

Dictionary Items

Dictionary items are ordered, changeable, and does not allow duplicates.

Dictionary items are presented in key:value pairs, and can be referred to by using the
key name.

Operations on List in python


• Access Items
• Access values
• Access keys
• Check if Item Exists
• Change Item Value
• add Item
• Remove Specified Item
• Clear the List
• Copy the list

Accessing Items
You can access the items of a dictionary by referring to its key name, inside
square brackets:

Example

Get the value of the "model" key:

D1 = {
"name": "lavanya",
"class": "bca",
"regno": 1001
}
print(D1["name"])

Output:

Lavanya

Get Keys
The keys() method will return a list of all the keys in the dictionary.

D1 = {
"name": "lavanya",
"class": "bca",
"regno": 1001
}
print(D1.keys())

output:

dict_keys(['name', 'class', 'regno'])

Get Values
The values() method will return a list of all the values in the dictionary.

D1 = {
"name": "lavanya",
"class": "bca",
"regno": 1001
}
print(D1.keys())
output:

dict_values(['lavanya', 'bca', 1001])

Get Items
The items() method will return each item in a dictionary, as tuples in a list.

D1 = {
"name": "lavanya",
"class": "bca",
"regno": 1001
}
print(D1.items())

output:

dict_items([('name', 'lavanya'), ('class', 'bca'), ('regno', 1001)])

Check if Item Exists


To determine if a specified key is present in a dictionary use the in keyword:
In the above example

if "regno" in D1:
print("Yes, 'regno' is one of the keys in the D1 dictionary")

output:

Yes, 'regno' is one of the keys in the D1 dictionary

Change Values
You can change the value of a specific item by referring to its key name:

D1 = {
"name": "lavanya",
"class": "bca",
"regno": 1001
}
D1[“name”]=(“Bindu”)
print(D1)

Output:

{'name': 'Bindu', 'class': 'bca', 'regno': 1001}

Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a
value to it:

D1 = {
"name": "lavanya",
"class": "bca",
"regno": 1001
}

D1[“address”]=(“Bangalore”)
print(D1)

Output:

{'name': 'lavanya', 'class': 'bca', 'regno': 1001, 'address': 'Bangalore'}

Removing Items
There are several methods to remove items from a dictionary:

Example

The pop() method removes the item with the specified key name:

D1 = {
"name": "lavanya",
"class": "bca",
"regno": 1001
}

D1.pop(‘regno’)

Print(D1)

Output:

{'name': 'lavanya', 'class': 'bca'}


Copy a Dictionary
You cannot copy a dictionary simply by typing D2= D1, because: D2 will only be
a reference to D1, and changes made in D1 will automatically also be made in D2.

There are ways to make a copy, one way is to use the built-in Dictionary
method copy().

D1 = {
"name": "lavanya",
"class": "bca",
"regno": 1001
}
D2=D1
print(D2)

Output:

{'name': 'lavanya', 'class': 'bca', 'regno': 1001}

Dictionary Methods
Python has a set of built-in methods that you can use on dictionaries.

Method Description

clear() Removes all the elements from the dictionary

copy() Returns a copy of the dictionary

fromkeys() Returns a dictionary with the specified keys and value


get() Returns the value of the specified key

items() Returns a list containing a tuple for each key value pair

keys() Returns a list containing the dictionary's keys

pop() Removes the element with the specified key

popitem() Removes the last inserted key-value pair

setdefault() Returns the value of the specified key. If the key does not exist:
insert the key, with the specified value

update() Updates the dictionary with the specified key-value pairs

values() Returns a list of all the values in the dictionary

', 'banana', 'cherry', 'kiwi', 'orange']


['apple', 'banana', 'cherry', 'kiwi', 'orange']
Loop Through a Dictionary(traversing through dictionary)
You can loop through a dictionary by using a for loop.

When looping through a dictionary, the return value are the keys of the dictionary,
but there are methods to return the values as well.

Example:

Print all key names in the dictionary, one by one:

D1 = {
"name": "lavanya",
"class": "bca",
"regno": 1001
}

for x in D1:
print(x)

output:

name

class

regno

Example2:

D1 = {
"name": "lavanya",
"class": "bca",
"regno": 1001
}

for x in D1:
print(D1[x])

output:

lavanya

bca

1000

You might also like