0% found this document useful (0 votes)
67 views14 pages

Unit Iv

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)
67 views14 pages

Unit Iv

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/ 14

UNIT-4

LISTS, TUPLES, DICTIONARIES

Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list parameters;
Tuples: tuple assignment, tuple as return value; Dictionaries: operations and methods; advanced list
processing - list comprehension; Illustrative programs: simple sorting, histogram, Students marks statement,
Retail bill preparation

LISTS:

• List is a sequence of values. Values in the list are called elements or items.
• String is also sequence of values. String is sequence of characters. List is the values of any type.
• These elements are separated by commas and enclosed within the square bracket.

For example
[10,20,30,40] # list of integers
[‘aaa’,’bbb’,’ccc’] #list of strings
[‘a’,10,20,’b’,33.33] #mixed list
The list that contains no element is called empty list. The empty list is represented by []

List Operations

There are two operations that can be performed using operators such as + and *

1. Concatenation using +
The two lists can be created and can be joined using + operator.
>>> L1=[10,20,30,40,50]
>>> L2=[60,70,80,90]
>>> L=L1+L2
>>> L
[10, 20, 30, 40, 50, 60, 70, 80, 90]

2. Repetition using *
The * is used to repeat the list for number of times.
>>> L=[10,20,30]
>>> L*3
[10, 20, 30, 10, 20, 30, 10, 20, 30]
List Slices

The : operator used within the square bracket is a list slice

>>> a=[10,20,30,40,50,60]
>>> a[1:4]
[20, 30, 40]
>>> a[:5]
[10, 20, 30, 40, 50]
>>> a[4:]
[50, 60]
>>> a[:]
[10, 20, 30, 40, 50, 60]

If we omit the first index then the list is considered from the beginning. And if we omit the last second index
then slice goes to end. If we omit both the first and second index then the list will be displayed from the
beginning to end. Lists are mutable. That means we can change the elements of the list

For example

>>> a=[10,20,30,40,50]
>>> a[2:4]=[11,22,33]
>>> a
[10, 20, 11, 22, 33, 50]

List Methods

1) append() : This method is to add the element at the last position of the list.

Syntax: list.append(element)

Example:
>>> a=[10,20,30]
>>> a.append(40) #adding element 40 at the end
>>> a
[10, 20, 30, 40]

2) extend(): The extend function takes the list as an argument and appends this list at the end of old list.
Syntax: List1.extend(List2)

Where List2 is added at the end of List1

Example:
>>> a=[10,20,30]
>>> b=['a','b','c']
>>> a.extend(b)
>>> a
[10, 20, 30, 'a', 'b', 'c']

3. insert() : This function allows to insert the desired element at specified position.

Syntax : List.insert(position, element)

Where the first parameter is a position at which the element is to be inserted. The element to be inserted is
the second parameter in this function.

Example :
a=[10,20,30]
a.insert(2,25)
print("List a = ",a)
Output will be
List a = [10, 20, 25, 30]

4. remove : The remove method deletes the element which is passed as a parameter. It actually removes the
first matching element.

Syntax : List.remove(element)

Example :
>>> a=[10,20,30,20,40,50]
>>> a.remove(20)
>>> print(a)
[10, 30, 20, 40, 50]

5. erase() : This method erases all the elements of the list. After this operation the list becomes empty.

Syntax : List.clear()
Example :
>>> a=[10,20,30,40,50]
>>> a.clear()
>>> print(a)
[]

6. sort() : This method sorts or arranges the elements in increasing order

Syntax: List.sort()

Example :
>>> a=['x','z','u','v','y','w']
>>> a.sort()
>>> a
['u', 'v', 'w', 'x', 'y', 'z']

7. reverse() : This method is for reversing the elements in the list.

Syntax: List.reverse()

Example :
>>> a=[10,20,30,40,50]
>>> a.reverse()
>>> print("List after reversing is: ",a)
List after reversing is: [50, 40, 30, 20, 10]

8. count() : This method returns a number for how many times the particular element appears in the list.

Syntax : List.count(element)

Example :
>>> a=[10,20,10,30,10,40,50]
>>> print("Count for element 10 is: ",a.count(10))
Count for element 10 is: 3

9. len() : This function returns the number of items present in the list

Syntax: len(List)
Example :
>>> a=[10,20,30,40,50]
>>> len(a)
5

10. max() : This function returns the maximum value element from the list.

Syntax: max(iterable)

The maximum value from the iterable is returned.

Example :
>>> a=[1,2,3,55,7]
>>> print(max(a))
55

11. min() : This function returns the minimum value element from the list.

Syntax: min(iterable)

The minimum value from the iterable is returned.

Example :
>>> a=[100,10,1,20,30]
>>> print(min(a))
1

12. sum() : This function adds the items of iterable and the sum is retunred.

Syntax : Sum(list)

Example :
>>> a=[1,2,3,4]
>>> result=sum(a)
>>> print(result)
10
List Loop

The Loop is used in list for traversing purpose. for loop is used to traverse the list elements

Syntax

for VARIABLE in LIST :


Body of For Loop
Example
>>> a=['a','b','c','d','e'] # List a is created
>>> for i in a:
print(i)

Output:
a
b
c
d
e

Mutability

Strings are immutable. That means, we can not modify the strings.
But Lists are mutable. That means it is possible to change the values of list.

For example

>>> a=['AAA','BBB','CCC']

>>> a[1]='XXX'

>>> a

['AAA', 'XXX', 'CCC']

Aliasing

Definition: An object with more than one reference has more than one name, then the object is aliased.
For example -

>>> x=[10,20,30]
>>> y=x
>>> y is x
True
>>> y
[10, 20, 30]

For example –

>>> x=[10,20,30]
>>> y=x
>>> y
[10, 20, 30]
>>> y[0]=111
>>> y
[111, 20, 30]
>>> x
[111, 20, 30]

Cloning Lists

Cloning means creating exact replica of the original list. Methods used to clone the list are

1. Cloning by assignment

2. Cloning by Slicing

Cloning by assignment

We can assign one list to another new list. This actually creates a new reference to the original list.

For example
>>> a=['a','b','c']
>>> b=a
>>> b
['a', 'b', 'c']
Cloning by Slicing

[:] operator is used for creating the clone by slicing.

For example

>>> a=[10,20,30]

>>> b=a[:]

>>> print(b)

[10, 20, 30]

List Parameters

A list can be passed as a parameter to function. This parameter is passed by reference. That means
any change made in the list inside function will affect list even after returning function to main.
>>> def insert(a):
a.append(40)
>>> a=[10,20,30]
>>> insert(a)
>>> a
[10, 20, 30, 4]

TUPLES:

Tuple is a sequence of values. It is similar to list but there lies difference between tuple and list

Difference between Tuple and List


• Tuple use parenthesis List use square brackets
• Tuples can not be change Lists can be changed.
• Tuple is said to immutable. That means once created we can not change the tuple.

Examples of tuples
T1 = (10,20,30,40)
T2 = (‘a’,’b’,’c’,’d’)
T3 = (‘A’,10,20)
T4 = (‘aaa’,’bbb’,30,40)
The tuple index starts at 0. For example
>>> t1=(10,20,'AAA','BBB')
>>> print(t1[0])
10
>>> print(t1[1:3])
(20, 'AAA')

Tuple Assignment

Create a tuple by using assignment operator. Multiple assignments are possible using tuple assignment.

For example –

>>> a,b=10,20
>>> print(a)
10
>>> print(b)
20

Tuple as Return Value

Function return a single value, but if the value is tuple, then multiple values can be returned.

For example – Test.py

>>> def student():


name='Rithani'
roll=101
return name,roll
>>> t=student()
>>> print(t[0])
Rithani
>>> print(t[1])
101
Dictionaries

Definition :
• Dictionary is unordered collection of items. These items are in form of key-value pairs.
• Dictionary contains the collection of indices called keys and collection of values.
• The association of keys with values is called key-value pair or item.

Fig. Dictionaries
How to Create Dictionary

• Items of the dictionary are written within the {} brackets and are separated by commas
• Key value pair is represented using : operator. That is key:value
• Keys are unique and are of immutable types – such as string, number, tuple.

Example:

>>> mydict={'name':'Rithani','age':'5'}
>>> mydict
{'name': 'Rithani', 'age': '5'}
>>> print(mydict)
{'name': 'Rithani', 'age': '5'}
>>> print(mydict['name'])
Rithani
>>> print(mydict['age'])
5
Operations and Methods

Basic Operations: Various operations that can be performed on dictionary are:

1. Adding item to Dictionary

2. Remove item from Dictionary

3. Updating the value of the dictionary

4. Checking length
Methods in Dictionary

1. Adding item to Dictionary: We can add the item to the dictionary.

For example
>>> my_dictionary={0:'Red',1:'Green',2:'Blue'}
>>> print(my_dictionary)
{0: 'Red', 1: 'Green', 2: 'Blue'}
>>> my_dictionary[3]='Yellow'
>>> print(my_dictionary)
{0: 'Red', 1: 'Green', 2: 'Blue', 3: 'Yellow'}
2. Remove item from Dictionary

For removing an item from the dictionary we use the keyword del.

For example

>>> del my_dictionary[2]


>>> print(my_dictionary)
{0: 'Red', 1: 'Green', 3: 'Yellow'}
>>>
3. Updating the value of the dictionary

We can update the value of the dictionary by directly assigning the value to corresponding key position.

For example -
>>> my_dictionary={0:'Red',1:'Green',2:'Blue'}
>>> print(my_dictionary)
{0: 'Red', 1: 'Green', 2: 'Blue'}
>>> my_dictionary[1]='Yellow'
>>> print(my_dictionary)
{0: 'Red', 1: 'Yellow', 2: 'Blue'}

4. Checking length

The len() function gives the number of pairs in the dictionary. For example
>>> my_dictionary=dict({0:'Red',1:'Green',2:'Blue'})
>>> len(my_dictionary)
3
Methods in Dictionary

1. The clear method

This method removed all the items from the dictionary.


For example
>>> my_dictionary={1:'AAA',2:'BBB',3:'CCC'} # creation of dictionary
>>> print(my_dictionary) #display
{1: 'AAA', 2: 'BBB', 3: 'CCC'}
>>> my_dictionary.clear() #using clear method
>>> print(my_dictionary) #display
{}
>>>

2. The copy method

The copy method returns the copy of the dictionary.


It does not take any parameter and returns a shallow copy of dictionary.
For example
>>> my_dictionary={1:'AAA',2:'BBB',3:'CCC'}
>>> print(my_dictionary)
{1: 'AAA', 2: 'BBB', 3: 'CCC'}
>>> new_dictionary=my_dictionary.copy()
>>> print(new_dictionary)
{1: 'AAA', 2: 'BBB', 3: 'CCC'}
>>>
Illustrative programs:

1. Sorting:

#Initialize array

arr = [5, 2, 8, 7, 1];

temp = 0;

#Displaying elements of original array

print("Elements of original array: ");

for i in range(0, len(arr)):

print(arr[i], end=" ");

#Sort the array in ascending order

for i in range(0, len(arr)):

for j in range(i+1, len(arr)):

if(arr[i] > arr[j]):

temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

#Displaying elements of the array after sorting

print("Elements of array sorted in ascending order: ");

for i in range(0, len(arr)):

print(arr[i], end=" ");

Output:

Elements of original array:

5 2 8 7 1

Elements of array sorted in ascending order:

1 2 5 7 8
2. Students marks statement program:
mark.py
print("Enter Marks Obtained in 5 Subjects: ")
M1 = int(input())
M2 = int(input())
M3 = int(input())
M4 = int(input())
M5 = int(input())
tot = M1+M2+M3+M4+M5
avg = tot/5
print("Total is",tot)
print("Average is",avg)
if avg>=90 and avg<=100:
print("Your Grade is A")
elif avg>=80 and avg<91:
print("Your Grade is B")
elif avg>=70 and avg<81:
print("Your Grade is C")
elif avg>=60 and avg<71:
print("Your Grade is D")
elif avg>=50 and avg<61:
print("Your Grade is E")
elif avg<50:
print("YOUR ARE FAIL")
Output:
Enter Marks Obtained in 5 Subjects:
96
52
36
98
89
Total is 371
Average is 74.2
Your Grade is C

You might also like