LISTS,TUPLES,DICTION
ARIES
Lists:-
• A list is a sequence of values.
• They can be of any datatype.
• The values in a list are called elements or items.
• There are several ways to create a list
1.The simplest way is enclose the elements in square brackets([and ])
Example:-
Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
2.A list that contains no elements is called empty list.
It can be created with empty brackets[].
Example:-
Create a List:
Empty=[]
3.A list contain elements of another list is called nested list.
Example:-
[“ Saran”,10,[15,25,35]]
Assigning list values to variables:-
• The list variables can be assigned to variables.
Example:-
>>>Icecreams=[‘vannila’’,strawberry’,’mango’]
>>>Age=[20,21,22,23,24,25]
>>>print(Icecreams,Age)
[‘vannila’’,strawberry’,’mango’] [20,21,22,23,24,25]
Accessing list elements:-
• The expression inside the brackets specifies the index.
• The index starts at 0
Example:-
>>>Icecreams=[‘vannila’,’strawberry’,’mango’]
>>> Icecreams[0]
‘vannila’
>>> Icecreams[1]
‘strawberry’
Negative indexing:-
• Python allows negative indexing for its sequences.
• The index -1 refers to the last item,-2 to next item and so on.
Example:-
>>>Icecreams=[‘vannila’,’strawberry’,’mango’]
>>> Icecreams[-1]
’mango’
List methods:-
append()
Adds a single item to the bottom of the list.
x = [1, 2]
x.append('h')
print(x)
Output:
[1, 2, 'h’]
Count()
The count method returns the number of times the items appear in the list.
x = [‘a’,’p’,’p’,’l’,’e’]
x.count(‘p')
print(x)
Output:
2
extend()
Adds another list to the end of a list.
x = [1, 2]
x.extend([3, 4])
print(x)
Output:
[1, 2, 3, 4]
insert()
Inserts a new element at a specific position in the list, this method receives the
position as a first argument, and the element to add as a second argument .
x = [1, 2]
x.insert(0, 'y')
print(x)
Output:
['y', 1, 2]
del()
• Deletes the element located in the specific index.
Program:-
x = [1, 2, 3]
del x([1])
print(x)
Output:
[1, 3]
len()
The len() returns number of elements in the list
Program:-
x = [1, 2, 3,4,5,6,7,8,9,10,21,22,23]
s=len(x)
print(s)
Output:
13
remove()
Removes the first match for the specified item.
x = [1, 2, 'h', 3, 'h']
x.remove('h')
print(x)
Output:
[1, 2, 3, 'h’]
reverse()
Reverses the order of the elements in the list, this places the final
elements at the beginning, and the initial elements at the end.
x = [1, 2, 'h', 3, 'h']
x.reverse()
print(x)
Output:
['h', 3, 'h', 2, 1]
Sort()
By default, this method sorts the elements of the list from smallest to largest,
this behavior can be modified using the parameter reverse = True.
Program1:
x = [3, 2, 1, 4]
x.sort()
print(x)
Output:
[1, 2, 3, 4]
Program2:
max()
The max() function returns the maximum value from the list.
Program:-
x = [1, 2, 3,4,5,6,7,8,9,10,21,22,23]
S=max(x)
print(S)
Output:
23
min()
The max() function returns the minimum value from the list.
Program:-
x = [1, 2, 3,4,5,6,7,8,9,10,21,22,23]
S=min(x)
print(S)
Output:
1
List Slices:-
• An individual element in list is called slice.
• Selecting a slice is similar to selecting an elements of a list.
Index between the elements:-
Index from left 0 1 2 3
List elements Pen Pencil Rubber scale
Index from right -4 -3 -2 -1
Program1:-
x = [1, 2, 3,4,5,6,7,8,9,10,21,22,23]
s=x[2:5]
print(s)
Output:
[3, 4, 5]
Program2:-
x = [1, 2, 3,4,5,6,7,8,9,10,21,22,23]
s=x[:5]
print(s)
Output:
[1, 2, 3, 4, 5]
Program3:-
x = [1, 2, 3,4,5,6,7,8,9,10,21,22,23]
s=x[2:]
print(s)
Output:
[3, 4, 5, 6, 7, 8, 9, 10, 21, 22, 23]
Program4:-
x = [1, 2, 3,4,5,6,7,8,9,10,21,22,23]
s=x[:-2]
print(s)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 21]
Program5:-
x = [1, 2, 3,4,5,6,7,8,9,10,21,22,23]
s=x[-5:-2]
print(s)
Output:
[9, 10, 21]
Program6:-
x = [1, 2, 3,4,5,6,7,8,9,10,21,22,23]
s=x[-5:]
print(s)
Output:
[9, 10, 21, 22, 23]
List operations:-
Concatenation operation:-
• concatenation means joining two operands.
• + operator concatenate two lists with each other and produce the third list.
Program:-
a=[1,2,3]
b=[4,5,6]
c=a+b
print(c)
Output:-
[1, 2, 3, 4, 5, 6]
Repeat operation:-
• Lists can be replicate or repeated or repeatedly concatenated with the asterisk
operator “*”.
• The * operator repeats a list in a given number of times.
Program:-
a=[1,2,3]*3
print(a)
Output:-
[1, 2, 3, 1, 2, 3, 1, 2, 3]
LIST LOOP(TRAVERSING A LIST):-
1.Traversing a list means ,process or go through each element of a list sequentially.
Syntax:-
for<list_items> in <List>:
Statement to process
<list_items>
Program:-
icecreams=["vennila","strawberry","mango","chocolate"]
for icecreams in icecreams:
print(icecreams)
Output:-
vennila
strawberry
mango
chocolate
2.The ‘for loop’ works well to read the elements of the list. But to write or update the elements, it is
needed to specify the indices.
A common way to do that is to combine the built-in functions range and len.
Syntax:
for<index> in range(len(list)):
statement to process
<List[index]>
Example:
Program:-
icecreams=["vennila","strawberry","mango","chocolate"]
for i in range(len(icecreams)):
print(icecreams[i])
Output:-
vennila
strawberry
mango
chocolate
3.A ‘for loop’ over an empty list never runs the body.
for x in[]:
print(“This never happens”)
4.The nested list will be considered as a single element.
Program:-
icecreams=["vennila","strawberry",["mango","chocolate“]]
Print(len(icecreams))
Output:-
3
Mutability:-
• The list is changeable, meaning that we can change, add, and
remove items in a list after it has been created.
• An object whose internal state can be changed is called a mutable object.
• The following are examples of mutable objects:
Lists
Sets
Dictionaries
Program:-
birds=[“parrot”,”pigeon”,”dove”,”owl”,”penguin”]
print(birds)
birds[1]=“duck”
birds[3]=“hen”
print(birds)
Output:-
[“parrot”,”pigeon”,”dove”,”owl”,”penguin”]
[“parrot”,”duck”,”dove”,”hen”,”penguin”]
State diagram:-
• birds
0 parrot
1 pigeon
duck
2 dove
3 owl
hen
4 penguin
Immutable :-
Internal state cannot be changed is called an immutable object.
• The following are examples of immutable objects:
Numbers (int, float, bool,…)
Strings
Tuples
Frozen sets
Strings are immutable:-
It means the content of the string cannot be changed after it has been created.
Program:
s="python"
s[0]="P"
print(s)
Ouput:-
Traceback (most recent call last):
File "C:/Users/LENOVO/AppData/Local/Programs/Python/Python312/qqq.py",
line 2, in <module>
s[0]="P"
TypeError: 'str' object does not support item assignment
Aliasing:-
• Aliasing is a circumstance when two or more variables refers to the same object.
• The same list has two different names.
• Changes made with one alias affect the other.
Program:-
list=["a","b","c","d"]
temp=list
print(list)
print(temp)
temp.append("e")
print(list)
print(temp)
Output:-
['a', 'b', 'c', 'd']
['a', 'b', 'c', 'd']
['a', 'b', 'c', 'd', 'e']
Cloning list:-
• Cloning a list is to make a copy of the list itself.
• The easiest way to clone a list is to use the slice operator.
• The change made in the cloned list will not be reflected back in the original list.
Program:
list=["a","b","c","d"]
temp=list[:]
print(list)
print(temp)
temp.append("e")
print(list)
print(temp)
Output:
['a', 'b', 'c', 'd']
['a', 'b', 'c', 'd']
['a', 'b', 'c', 'd']
['a', 'b', 'c', 'd', 'e']
List parameters:-
• Passing a list as an arguments actually passes a reference to the list, not a copy
of the list.
• If a function modifies a list ,the caller see the changes.
Program:-
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
Output:-
apple
banana
cherry
Tuples:-
• A tuple is a sequence of values, which can be of any type and they are indexed
by integer.
• Tuples are an immutable sequence of elements. That is once a tuple is defined,
it cannot be altered.
• It is not necessary to enclose tuples in parenthesis.
• Example:
fruits = ("apple", "banana", "cherry“)
or
fruits = "apple", "banana", "cherry"
Creation of tuples:-
1.To create a tuple with a single element, include a final comma.
T1=‘banana’,
print(T1)
O/P
('banana',)
2.A tuple can be created using the built in function tuple. It can be an empty
tuple with no arguments.
T=tuple()
Print(T)
O/P
()
3.A tuple built in function can be used to create a tuple with sequence of arguments.
T=tuple('good students')
print(T)
O/P
('g', 'o', 'o', 'd', ' ', 's', 't', 'u', 'd', 'e', 'n', 't', 's’)
Operators on tuple:-
1.Bracket operator
The bracket operator indexes an element.
T=tuple('good students')
print(T[0])
print(T[1])
print(T[2])
print(T[3])
O/P:
g
o
o
Slice operator:-
The slice operator selects arrange of elements.
T=('good students')
print(T[5:10])
O/P:-
('s', 't', 'u', 'd', 'e’)
Concatenation operator:-
Tuples can be concatenated or joined them using + operator.
T1=('good')
T2=('students')
T3=T1+T2
print(T3)
O/P
goodstudents
Relational operators:-
The relational operators work with tuples and other sequences.
t1=(1,2,1,4)
t2=(1,2,2,4)
print(t1<t2)
O/P
True
t1=(1,2,3,4)
t2=(1,2,2,4)
print(t1<t2)
O/P
False
Looping through tuples:-
Tuple elements can be traversed using loop control statements.
The for loop is best to traverse tuple elements.
T1=('g','o','o','d')
for val in T1:
print(val)
O/P
g
o
o
d
Tuple Assignment
• It allows a tuple of variables on the left side of the assignment operator to be
assigned respective values from a tuple on right side.
• The number of variables on the left side should be same as the number of
elements in the tuple.
Program:-
T1=('g','o','o','d')
T2=('s','t','u','d','e','n','t','s')
print(T1,T2)
O/P
('g', 'o', 'o', 'd') ('s', 't', 'u', 'd', 'e', 'n', 't', 's')
Tuple as return values:-
Function can return more than one value.
function that calculates the area and perimeter of a
rectangle:
def calculate_area_and_perimeter(length, width):
area = length * width
perimeter = 2 * (length + width)
return area, perimeter
Dictionary
• 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:
• 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.
Example
Print the "brand" value of the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
O/P:
Ford
Dictionary operations and methods:-
clear() Method
• Remove all elements from the list:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.clear()
print(car)
Output:-
{}
copy() Method
• Returns Copy the car dictionary:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.copy()
print(x)
Output:-
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
items() Method
Return the dictionary's key-value pairs:
Example:-
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x)
Output:-
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year',
1964)])
keys() Method
Return only the keys
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
print(x)
O/P:-
dict_keys(['brand', 'model', 'year'])
pop() method
• Removes the element with the specified keypop() Method
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.pop("model")
print(car)
Output:-
{'brand': 'Ford', 'year': 1964}
popitem() Method
• Remove the last item from the dictionary:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.popitem()
print(car)
Output:-
{'brand': 'Ford', 'model': 'Mustang'}
update() Method
Insert an item to the dictionary:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.update({"color": "White"})
print(car)
O/P:-
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color':
'White'}
values() Method
• Returns a list of all the values in the dictionary
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
Output:-
dict_values(['Ford', 'Mustang', 1964])
Advanced list processing(List Comprehension):-
• To create a new list from the existing list.
Syntax:
[expr for var in list if expr]
Program:
numbers=[-3,-2,-1,0,1,2,3]
s=[x for x in numbers if x>0]
print(s)
Output:-
[1, 2, 3]