Chapter 3-3
Chapter 3-3
Chapter 3
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
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))
Example
k=[]
for i in range(0,3):
el=input("enter value")
k.append(el)
print(k)
Example
k=[]
for i in range(0,3):
el=input("enter value")
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)
Example
k=[]
for i in range(0,3):
el=input("enter value")
k.append(el)
print(k)
print(k.reverse())
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:
break
else:
print("Invalid input")
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
Example
my_dict = {} # empty dictionary
OUTPUT:
{}
{1: 'apple', 2: 'ball'}
{'name': 'John', 1: [2, 4, 3]}
Example
my_dict = {'name': 'aaa', 'age': 26}
print(my_dict['name'])
print(my_dict.get('age'))
OUTPUT:
Jack
26
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.
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)])
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)])
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,…}
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)
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.
# set of integers
my_set = {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)