Problem Solving and Python Programming: UNIT IV: Lists, Tuples, Dictionaries

Lists

Syntax, Example Program | Python Programming

The values in the list are called elements or items. These elements are separated by commas and enclosed within the square bracket.

Lists

AU : Dec.-19, Marks 10

• List is a sequence of values.

• String is also sequence of values. But in string this sequence is of characters. On the other hand, in case of List the values can be of any type.

• The values in the list are called elements or items. 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

[10,20,['a','b','d']] #nested list

• The list within another list is called nested list.

• The list that contains no element is called empty list. The empty list is represented

by []

 

1. 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. Following screenshot illustrates it.


2. Repetition using *

The * is used to repeat the list for number of times. Following screenshot illustrates it.


 

2.  List Slices

•The : operator used within the square bracket that it is a list slice and not the index of the list

>>> 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. Hence it is always better to make a copy of the list before performing any operation.

• For example

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

>>> a[2:4]=[111,222,333]

>>> a

[10, 20, 111, 222, 333, 50)

>>> 

 

3. List Methods

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]

>>> b=['A', 'B', 'C']

>>> b.append('D') #adding element D at the end

>>> b

['A', 'B', 'C', 'D')

 >>>

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) pop() :

This function removes the element specified by the index.

Syntax :

List.pop(index)

The index represent the location of element in the list and the element specified by the index will be deleted and returned. The parameter passed to the list is optional. If no parameter is passed, the default index -1 is passed as an argument which returns the last element.

Example

#list created

a=[10,20,30,40,50]

ret_val=a.pop(2)

print("The deleted element is = ",ret_val)

print("The modified list is = ",a)

Output

The deleted element is = 30

The modified list is = [10, 20, 40, 50)

>>> 

Pop when no parameter is passed

Syntax

List.pop()

Example

#list created

a = [10,20,30,40,50]

ret_val=a.pop()

print("The deleted element is = ",ret_val)

print("The modified list is = ",a)

Output

The deleted element is = 50

The modified list is = [10, 20, 30, 40)

Pop() when negative parameter is passed

Syntax

List.pop(negative index)

Example

# Creation of list

a = (10,20,30,40,50]

# When -1 is passed

# Pops Last Element

print("\nWhen -1 is passed:')

print('Return Value:', a.pop(-1))

print('Updated List:', a)

 

# When -3 is passed

# Pops Third Last Element

print("\nWhen -3 is passed:')

print('Return Value: ', a.pop(-3))

print('Updated List:', a)

Output

When -1 is passed:

Return Value: 50

Updated List: [10, 20, 30, 40]

 

When -3 is passed:

Return Value: 20

Updated List: [10, 30, 40]

>>>

5) 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]

6) 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)

>>> 

7) del(): This method deletes all the elements within the given range.

Syntax :

List.del(a:b)

The element within the range a to b get deleted by this method.

Example :

>>> a=['a','b','c','d', 'e']

>>> del a[2:4]

>>> a

['a', 'b', 'e']

>>> 

8) 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']

>>> 

9) 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]

>>> 

10) 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

Built-in Functions For List

1) all() : This function returns true if all the elements of the list are true or if the list is empty.

Syntax :

all(iterable)

The all method returns true if all elements in iterable are true otherwise it returns false.

Example :

>>> a=(1,2,3,4] >>>

print(all(a))

True

>>> b=[1,2,0,3,4]

>>> print(all(b))

False

>>> c=[l

>>> print(all(c))

True

>>> 

2) any(): This method returns True if any element of an iterable is true. If not, this method returns False.

Syntax :

any(iterable)

The any method returns :

True if at least one element of an iterable is true

False if all elements are false or if an iterable is empty

When : Retum Value

All values are true : True

All values are false : False

One value is true (others are false) : True

One value is false (others are true) : True

Empty Iterable : False


Example :

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

>>> print(any(a))

True

>>> b=[ ]

>>> print(any(b))

False

>>> c=[False 01

>>>print(any(c))

False

>>> 

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

Syntax :

len(List)

Example :

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

>>> print("The length of list a is: ",len(a))

The length of list a is: 5

>>>

4) list(): This function converts an iterable to a list

Syntax :

list([iterable])

The list() constructor returns a mutable sequence list of elements.

If no parameters are passed, it creates an empty list

If iterable is passed as parameter, it creates a list of elements in the iterable

Example :

>>>print(list())

[ ]

>>> mystr="hello"

>>> print(list(mystr))

['h', 'e', 'T', 'T', 'o']

>>> mytuple=('h', 'e','T,T,'0')

>>> print(list(mytuple))

['h', 'e', 'T', 'T', 'o']

>>>

5) 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

 >>>

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

Syntax :

min(iterable)

The minimum value from the iterable is returned.

Example:

>>> a=1100,10,1,20,30]

>>>print(min(a))

1

>>> 

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

Syntax :

Sum(iterable, start)

The sum of all the elements from the iterable is returned. The start is optional. If start value is mentioned then it is added to the sum.

Example :

>>> a=[1,2,3,41

>>> result=sum(a)

>>> print(result)

10

>>>

start=100

>>> print(sum(a,start))

110

>>> 

 

4. List Loop

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

Syntax

for VARIABLE in LIST :

BODY

Example

>>> a=['a','b','c','d', 'e'] # List a is created

>>> for i in a: print(i)

will result into

a

b

c

d

e

>>> 

If me want to update the elements of the list, then we must pass index as argument to for loop. For example

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

>>> for i in range(len(a)):

a[i] = a[i]+1 #incremented each number by one

>>> a

[11, 21, 31, 41]

>>>

If we specify the [ ] empty list then the body of for loop will never get executed.

>>> for i in [1:

print("This line will never execute")

>>> 

 

5. 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.

• If the bracket operator is present on the left hand side, then that element is identified and the list element is modified accordingly.

For example

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

>>> a[1]='XXX

>>> a

['AAA', 'XXX', 'CCC')

>>>

Using the in operator we can check whether particular element belongs to the list or not. If the given element is present in the list it returns True otherwise False. For example

>>> a = ('AAA', 'XXX', 'CCC')

>>> 'XXX' in a

True

>>> 'BBB' in a

False

>>> 

 

6. Aliasing

Definition : An object with more than one reference has more than one name, so we say that the object is aliased.

For example -

>>> x = {10,20,30]

>>> y = x

>>> y is x

True

>>> y

[10, 20, 30]

>>>

The association of a variable with object is called reference.

In above example, reference y is created using object a. Diagrammatically aliasing is shown in Fig. 4.1.1.


Fig. 4.1.1 Aliasing

If any change is made in one reference then other object gets affected. For example

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

>>> y = x

>>> y

[10, 20, 30]

>>> y[0]=111

>>>y

[111, 20, 30]

>>> x

[111, 20, 30]

>>>

Note that in above list if we change the reference list y then the list x also gets changed automatically

 

7. Cloning Lists

Cloning means creating exact replica of the original list. There are various method using which we can clone the list.

1. 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']

>>> 

Note that here list bis a clone of original list a. But as the reference is created change in one list causes change in another list.

2. Cloning by slicing

We can create a clone by slicing. During this process, [:] operator is used for creating the clone. For example

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

>>> b = a[:]

>>> print(" List a =",a)

List a = [10, 20, 30]

>>> print(" List b=",b)

List b= [10, 20, 30]

>>> b[1]=222

>>> print("List b= ",b)

 List b= [10, 222, 30]

>>> print("List a="/a)

List a= [10, 20, 30]

>>>

Note that the clone b is created from the list a. But change in one list does not affect the other list

The operator [:] means copy the elements in one list from beginning to end into another list.

3. Clone by copy constructor

We can create a clone for the list using copy constructor. This is just similar to clone by slicing. The list function is used to create the clone. For example

>>> a = ['A','B','C']

>>> b = list(a)

>>> b

['A', 'B', 'C']

>>> a

['A', 'B', 'C']

>>>

Note that even if we make changes in the clone list, the other list does not get changed. For example

>>> a

['A', 'B', 'C']

>>> b[1]='Z

>>> b

['A', 'Z', 'C')

>>> a

['A', 'B', 'C']

>>> 

 

8.  List Parameters

A list can be passed as a parameter to the function. This parameter is passed by reference. That means any change made in the list inside the function will affect the list even after returning the function to the main.

For example :


In above screen-shot, the python code is written in interactive mode. The function Insert_End is for inserting the element at the end of the list.

Here we pass the list a as parameter to the function. Inside the function, the element is added at the end of the list. Hence after the making call to the function, we get the list in which the element is inserted at the end.

 

Example 4.1.1 Write a Python program to remove duplicates from a list

Solution :

a = [1,2,3,2,1,4,5,4,8,5,4]

duplicates = set()

for x in a:

if x not in duplicates :

duplicates.add(x)

print(duplicates)

Output


 

Example 4.1.2 Write a Python program to read a list of words and return the length of longest one

Solution :

a = [ ]

print("Enter the number of words in list:")

n = int(input())

 

for i in range(0,n):

item = input("Enter word" + str(i+1) + ":")

a.append(item)

max_len = len(a[0])

temp = a[0]

for i in a:

if(len(i) > max_len):

max_len = len(i)

temp = i

print("The longest length word is ")

print(temp)

 

Example 4.1.3 Write a Python program to print the maximum among 'n' randomly generate 'd numbers by storing them in a list.

AU : Dec.-19, Marks 10

Solution :

import random

def Max_from_random(s,e,n):

ran = [ ]

for i in range(n):

ran.append(random.randint(s, e))

print("The generated numbers are: ",ran)

max_num = ran[0]

for ele in ran:

if(ele>max_num):

max_num = ele

return max_num

 

# Driver Code

n = int(input("How many Random Numbers want to disaply ::'))

s = int(input("Enter Starting number ::"))

e = int(input("Enter Ending number ::"))

print(Max_from_random(s, e, n))

Output

How many Random Numbers want to disaply ::10

Enter Starting number ::1

Enter Ending number ::10

The generated numbers are: (8, 2, 4, 9, 7, 4, 2, 6, 8, 5]

9

>>> 

 

Example 4.1.4 Write a Python program to rotate a list by right n times with and without slicing technique.

AU : Dec.-19, Marks 4+4

Solution :

arr1 = [1, 2, 3, 4, 5]

print("Original List : " + str(arr1))

print("Rotating a list by 3 using slicing technique")

arr1 = arr1[-3:] + arr1[:-3]

print(arr1)

arr2 = [11,22,33,44,55]

print("Original List : " + str(arr2))

n = 3

print("Rotating a list by 3 without using slicing technique")

for i in range(0,n):

last = arr2[len(arr2)-1]

for j in range (len(arr2)-1,-1,-1):

#shift element of array by one

arr2[j] = arr2[j-1]

arr2[0] = last

print(arr2)

Output

Original List : [1, 2, 3, 4, 5]

Rotating a list by 3 using slicing technique

[3, 4, 5, 1, 2]

Original List : [11, 22, 33, 44, 55]

Rotating a list by 3 without using slicing technique

[33, 44, 55, 11, 22]

Review Questions

1. Discuss different options to traverse a list.

AU : Dec.-19, Marks 8

2. Demonstrate the working of +, * and slice operators in python.

AU : Dec.-19, Marks 8

3. How will you update list items ? Give one example.

AU : Dec.-19, Marks 2

4. Compare lists and arrays with example. Can list be considered as an array? Justify.

AU : Dec.-19, Marks 6

 

Problem Solving and Python Programming: UNIT IV: Lists, Tuples, Dictionaries : Tag: Engineering Python : Syntax, Example Program | Python Programming - Lists