UNIT3 Python
UNIT3 Python
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]
print(list1)
print(list2)
print(type(list1))
Output:
[1, 2, 'Python', 'Program', 15.9]
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
List items are indexed and you can access them by referring to the index number:
Example:
-1 refers to the last item, -2 refers to the second last item etc.
Example:
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:
output:
Output:
Example:
Output:
["apple", "banana”, “grapes”, "cherry"]
5.Append Items
To add an item to the end of the list, use the append() method:
Output:
["apple", "banana”, "cherry”, “mango”]
Output:
["apple", "banana”, "cherry”, “kiwi”, “orange”]
Output:
["apple", "cherry”]
Example
Output:
["banana", "cherry”]
If you do not specify the index, the pop() method removes the last item.
Example
Output:
[“apple”, "banana"]
Example
Output:
[]
Example:
Output:
Example:
Output:
[23,50,65,82,99]
Sort Descending
Output:
Example
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
Output:
output:
Example:
Output:
apple
banana
cherry
List Methods
Python has a set of built-in methods that you can use on lists.
Method Description
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
Nested lists
Example:
Print(Nested_List1)
Output:
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
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 = []
Output:
Initial stack
['a', 'b', 'c']
Elements popped from stack:
c
b
a
Elements can be inserted at one end called rear, elements can be deleted at
another end called front
2 4 6 7 8 10
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)
Output:
Initial queue
['a', 'b', 'c']
Tuple
Tuples are used to store multiple items in a single variable.
Example
Create a Tuple:
Characteristics of tuple
Tuple Items
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
Output:
To determine how many items a tuple has, use the len() function:
Example
Output:
3
Example
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
Output:
cherry
Output
Example
Output:
Tuple Methods
Python has two built-in methods that you can use on tuples.
Method Description
Count() method
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.
Example
Create a Set:
Output:
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.
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.
for x in Set1:
print(x)
Output:
cherry
banana
apple
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 Sets
To add items from another set into the current set, use the update() method.
4.Remove Item
To remove an item in a set, use the remove(), or the discard() method.
Example:
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.
output:
set()
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:
output:
Example
Return a set that contains the items that exist in both set x, and set y:
z = x.intersection(y)
print(z)
output:
{‘apple’}
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:
output:
{“banana”,”cherry”}
Python has a set of built-in methods that you can use on sets.
Method Description
Dictionaries are written with curly brackets, and have keys and values:
d1={'name':'lavanya','class':'bca','regno':1001}
print(d1)
Output:
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.
Accessing Items
You can access the items of a dictionary by referring to its key name, inside
square brackets:
Example
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:
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:
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:
if "regno" in D1:
print("Yes, 'regno' is one of the keys in the D1 dictionary")
output:
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:
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:
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:
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:
Dictionary Methods
Python has a set of built-in methods that you can use on dictionaries.
Method Description
items() Returns a list containing a tuple for each key value pair
setdefault() Returns the value of the specified key. If the key does not exist:
insert the key, with the specified value
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:
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