Home | | Computer Science 12th Std | Introduction to List

Python - Introduction to List | 12th Computer Science : Chapter 9 : Python Modularity and OOPS : Lists, Tuples, Sets And Dictionary

Chapter: 12th Computer Science : Chapter 9 : Python Modularity and OOPS : Lists, Tuples, Sets And Dictionary

Introduction to List

Python programming language has four collections of data types such as List, Tuples, Set and Dictionary.

Introduction to List

Python programming language has four collections of data types such as List, Tuples, Set and Dictionary. A list in Python is known as a “sequence data type” like strings. It is an ordered collection of values enclosed within square brackets [ ]. Each value of a list is called as element. It can be of any type such as numbers, characters, strings and even the nested lists as well. The elements can be modified or mutable which means the elements can be replaced, added or removed. Every element rests at some position in the list. The position of an element is indexed with numbers beginning with zero which is used to locate and access a particular element. Thus, lists are similar to arrays, what you learnt in XI std.

 

1. Create a List in Python

In python, a list is simply created by using square bracket. The elements of list should be specified within square brackets. The following syntax explains the creation of list.

Syntax:

Variable = [element-1, element-2, element-3 …… element-n]

Example

Marks = [10, 23, 41, 75]

Fruits = [“Apple”, “Orange”, “Mango”, “Banana”]

MyList = [ ]

In the above example, the list Marks has four integer elements; second list Fruits has four string elements; third is an empty list. The elements of a list need not be homogenous type of data. The following list contains multiple type elements.

Mylist = [ “Welcome”, 3.14, 10, [2, 4, 6] ]

In the above example, Mylist contains another list as an element. This type of list is known as “Nested List”.

Nested list is a list containing another list as an element.

 

2. Accessing List elements

Python assigns an automatic index value for each element of a list begins with zero. Index value can be used to access an element in a list. In python, index value is an integer number which can be positive or negative.


Positive value of index counts from the beginning of the list and negative value means counting backward from end of the list (i.e. in reverse order).

To access an element from a list, write the name of the list, followed by the index of the element enclosed within square brackets.

Syntax:

List_Variable = [E1, E2, E3 …… En]

print (List_Variable[index of a element])

  Example (Accessing single element):

>>>Marks = [10, 23, 41, 75]

>>>print (Marks[0])

10

 

In the above example, print command prints 10 as output, as the index of 10 is zero.

Example: Accessing elements in revevrse order

>>>Marks = [10, 23, 41, 75]

>>>print (Marks[-1])

75

Note: A negative index can be used to access an element in reverse order.

 

(i) Accessing all elements of a list

Loops are used to access all elements from a list. The initial value of the loop must be zero. Zero is the beginning index value of a list.

Example

Marks = [10, 23, 41, 75]

i = 0

while i < 4:

print (Marks[i])

i = i + 1

Output

10

23

41

75

In the above example, Marks list contains four integer elements i.e., 10, 23, 41, 75. Each element has an index value from 0. The index value of the elements are 0, 1, 2, 3 respectively. Here, the while loop is used to read all the elements. The initial value of the loop is zero, and the test condition is i < 4, as long as the test condition is true, the loop executes and prints the corresponding output.  

During the first iteration, the value of i is zero, where the condition is true. Now, the following statement print (Marks [i]) gets executed and prints the value of Marks [0] element ie. 10.

The next statement i = i + 1 increments the value of i from 0 to 1. Now, the flow of control shifts to the while statement for checking the test condition. The process repeats to print the remaining elements of Marks list until the test condition of while loop becomes false.

The following table shows that the execution of loop and the value to be print.


 

(ii) Reverse Indexing

Python enables reverse or negative indexing for the list elements. Thus, python lists index in opposite order. The python sets -1 as the index value for the last element in list and -2 for the preceding element and so on. This is called as Reverse Indexing.

Example

Marks = [10, 23, 41, 75]

i = -1

while i >= -4:

print (Marks[i])

i = i + -1

Output

75

41

23

10

The following table shows the working process of the above python coding


 

3. List Length

The len( ) function in Python is used to find the length of a list. (i.e., the number of elements in a list). Usually, the len( ) function is used to set the upper limit in a loop to read all the elements of a list. If a list contains another list as an element, len( ) returns that inner list as a single element.

 

Example :Accessing single element

>>>MySubject = [“Tamil”, “English”, “Comp. Science”, “Maths”]

>>>len(MySubject)

4

 

Example : Program to display elements in a list using loop

MySubject = ["Tamil", "English", "Comp. Science", "Maths"] i = 0

while i < len(MySubject):

print (MySubject[i])

i = i + 1

Output

Tamil

English

Comp. Science

Maths

 

4. Accessing elements using for loop

In Python, the for loop is used to access all the elements in a list one by one. This is just like the for keyword in other programming language such as C++.

Syntax:

for index_var in list:

print (index_var)

Here, index_var represents the index value of each element in the list. Python reads this “for” statement like English: “For (every) element in (the list of) list and print (the name of the) list items”

Example

Marks=[23, 45, 67, 78, 98]

for x in Marks:

print( x )

Output

23

45

67

78

98

In the above example, Marks list has 5 elements; each element is indexed from 0 to 4. The Python reads the for loop and print statements like English: “For (every) element (represented as x) in (the list of) Marks and print (the values of the) elements”.

 

5. Changing list elements

In Python, the lists are mutable, which means they can be changed. A list element or range of elements can be changed or altered by using simple assignment operator (=).

Syntax:

List_Variable [index of an element] = Value to be changed

List_Variable [index from : index to] = Values to changed

Where, index from is the beginning index of the range; index to is the upper limit of the range which is excluded in the range. For example, if you set the range [0:5] means, Python takes only 0 to 4 as element index. Thus, if you want to update the range of elements from 1 to 4, it should be specified as [1:5].

 

Python program to update/change single value

MyList = [2, 4, 5, 8, 10]

print ("MyList elements before update... ")

for x in MyList:

print (x)

MyList[2] = 6

print ("MyList elements after updation... ")

for y in MyList:

print (y)

Output:

MyList elements before update...

2

4

5

8

10

MyList elements after updation..

2

4

6

8

10

 

Python program to update/change range of values

MyList = [1, 3, 5, 7, 9]

print ("List Odd numbers... ")

for x in MyList:

print (x)

MyList[0:5] = 2,4,6,8,10

print ("List Even numbers... ")

for y in MyList:

print (y)

Output

List Odd numbers...

1

3

5

7

9

List Even numbers...

2

4

6

8

10

 

6. Adding more elements in a list

In Python, append( ) function is used to add a single element and extend( ) function is used to add more than one element to an existing list.

Syntax:

List.append (element to be added)

List.extend ( [elements to be added])

In extend( ) function, multiple elements should be specified within square bracket as arguments of the function.

Example

>>>Mylist=[34, 45, 48]

>>>Mylist.append(90)

>>>print(Mylist)

[34, 45, 48, 90]

In the above example, Mylist is created with three elements. Through >>> Mylist.append(90) statement, an additional value 90 is included with the existing list as last element, following print statement shows all the elements within the list MyList.

Example

>>>Mylist.extend([71, 32, 29])

>>>print(Mylist)

[34, 45, 48, 90, 71, 32, 29]

In the above code, extend( ) function is used to include multiple elements, the print statement shows all the elements of the list after the inclusion of additional elements.

 

7. Inserting elements in a list

As you learnt already, append( ) function in Python is used to add more elements in a list. But, it includes elements at the end of a list. If you want to include an element at your desired position, you can use insert ( ) function. The insert( ) function is used to insert an element at any position of a list.

Syntax:

List.insert (position index, element)

Example

>>>MyList=[34,98,47,'Kannan', 'Gowrisankar', 'Lenin', 'Sreenivasan' ]

>>>print(MyList)

[34, 98, 47, 'Kannan', 'Gowrisankar', 'Lenin', 'Sreenivasan']

>>>MyList.insert(3, 'Ramakrishnan')

>>>print(MyList)

[34, 98, 47, 'Ramakrishnan', 'Kannan', 'Gowrisankar', 'Lenin', 'Sreenivasan']

In the above example, insert( ) function inserts a new element ‘Ramakrishnan’ at the index value 3, ie. at the 4th position. While inserting a new element in between the existing elements, at a particular location, the existing elements shifts one position to the right.

 

8. Deleting elements from a list

There are two ways to delete an element from a list viz. del statement and remove( ) function. del statement is used to delete known elements whereas remove( ) function is used to delete elements of a list if its index is unknown. The del statement can also be used to delete entire list.

Syntax:

del List [index of an element]

#to delete a particular element

del List [index from : index to]

#to delete multiple elements

del List

#to delete entire list

Example

>>>MySubjects = ['Tamil', 'Hindi', 'Telugu', 'Maths']

>>>print (MySubjects)

['Tamil', 'Hindi', 'Telugu', 'Maths']

>>>del MySubjects[1]

>>>print (MySubjects)

['Tamil', 'Telugu', 'Maths']

In the above example, the list MySubjects has been created with four elements. print statement shows all the elements of the list. In >>> del MySubjects[1] statement, deletes an element whose index value is 1 and the following print shows the remaining elements of the list.

Example

>>>del MySubjects[1:3]

>>>print(MySubjects)

['Tamil']

In the above codes, >>> del MySubjects[1:3] deletes the second and third elements from the list. The upper limit of index is specified within square brackets, will be taken as -1 by the python.

Example

>>>del MySubjects

>>>print(MySubjects) Traceback (most recent call last):

File "<pyshell#9>", line 1, in <module> print(MySubjects)

NameError: name 'MySubjects' is not defined

Here, >>> del MySubjects, deletes the list MySubjects entirely. When you try to print the elements, Python shows an error as the list is not defined. Which means, the list MySubjects has been completely deleted.

As already stated, the remove( ) function can also be used to delete one or more elements if the index value is not known. Apart from remove( ) function, pop( ) function can also be used to delete an element using the given index value. pop( ) function deletes and returns the last element of a list if the index is not given.

The function clear( ) is used to delete all the elements in list, it deletes only the elements and retains the list. Remember that, the del statement deletes entire list.

Syntax:

List.remove(element)       # to delete a particular element

List.pop(index of an element)

List.clear( )

Example

>>>MyList=[12,89,34,'Kannan', 'Gowrisankar', 'Lenin']

>>>print(MyList)

[12, 89, 34, 'Kannan', 'Gowrisankar', 'Lenin']

>>>MyList.remove(89)

>>>print(MyList)

[12, 34, 'Kannan', 'Gowrisankar', 'Lenin']

In the above example, MyList has been created with three integer and three string elements, the following print statement shows all the elements available in the list. In the statement >>> MyList.remove(89), deletes the element 89 from the list and the print statement shows the remaining elements.

Example

>>>MyList.pop(1)

34

>>>print(MyList)

[12, 'Kannan', 'Gowrisankar', 'Lenin']

In the above code, pop( ) function is used to delete a particular element using its index value, as soon as the element is deleted, the pop( ) function shows the element which is deleted. pop( ) function is used to delete only one element from a list. Remember that, del statement deletes multiple elements.

Example

>>>MyList.clear( )

>>>print(MyList)

[ ]

In the above code, clear( ) function removes only the elements and retains the list. When you try to print the list which is already cleared, an empty square bracket is displayed without any elements, which means the list is empty.

 

9. List and range ( ) function

The range( ) is a function used to generate a series of values in Python. Using range( ) function, you can create list with series of values. The range( ) function has three arguments.

Syntax of range ( ) function:

range (start value, end value, step value)

where,

start value – beginning value of series. Zero is the default beginning value.

end value – upper limit of series. Python takes the ending value as upper limit – 1.

step value – It is an optional argument, which is used to generate different interval of values.

Example : Generating whole numbers upto 10

for x in range (1, 11):

print(x)

Output

1

2

3

4

5

6

7

8

9

10

Example : Generating first 10 even numbers

for x in range (2, 11, 2):

print(x)

Output

2

4

6

8

10

(i) Creating a list with series of values

Using the range( ) function, you can create a list with series of values. To convert the result of range( ) function into list, we need one more function called list( ). The list( ) function makes the result of range( ) as a list.

Syntax:

List_Varibale = list ( range ( ) )

Note

The list ( ) function is all so used to create list in python.

Example

>>>Even_List = list(range(2,11,2))

>>>print(Even_List)

[2, 4, 6, 8, 10]

In the above code, list( ) function takes the result of range( ) as Even_List elements. Thus, Even_List list has the elements of first five even numbers.

Similarly, we can create any series of values using range( ) function. The following example explains how to create a list with squares of first 10 natural numbers.

Example : Generating squares of first 10 natural numbers

squares = [ ]

for x in range(1,11):

s = x ** 2

squares.append(s)

print (squares)

In the above program, an empty list is created named “squares”. Then, the for loop generates natural numbers from 1 to 10 using range( ) function. Inside the loop, the current value of x is raised to the power 2 and stored in the variables. Each new value of square is appended to the list “squares”. Finally, the program shows the following values as output.

Output

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

 

10. List comprehensions

List comprehension is a simplest way of creating sequence of elements that satisfy a certain condition.

Syntax:

List = [ expression for variable in range ]

Example : Generating squares of first 10 natural numbers using the concept of List comprehension

>>>squares = [ x ** 2 for x in range(1,11) ]

>>>print (squares)

Output:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

In the above example, x ** 2 in the expression is evaluated each time it is iterated. This is the shortcut method of generating series of values.

 

11. Other important list function




 

12. Programs using List

Program 1: write a program that creates a list of numbers from 1 to 20 that are divisible by 4

divBy4=[ ]

for i in range(21):

if (i%4==0):

divBy4.append(i)

print(divBy4)

Output

[0, 4, 8, 12, 16, 20]

Program 2: Write a program to define a list of countries that are a member of BRICS. Check whether a county is member of BRICS or not

country=["India", "Russia", "Srilanka", "China", "Brazil"]

is_member = input("Enter the name of the country: ")

if is_member in country:

print(is_member, " is the member of BRICS")

else:

print(is_member, " is not a member of BRICS")

Output

Enter the name of the country: India

India is the member of BRICS

Output

Enter the name of the country: Japan

Japan is not a member of BRICS

Program 3: Python program to read marks of six subjects and to print the marks scored in each subject and show the total marks

marks=[]

subjects=['Tamil', 'English', 'Physics', 'Chemistry', 'Comp. Science', 'Maths'] for i in range(6):

m=int(input("Enter Mark = "))

marks.append(m)

for j in range(len(marks)):

print("{ }. { } Mark = { } ".format(j1+,subjects[j],marks[j]))

print("Total Marks = ", sum(marks))

Output

Enter Mark = 45

Enter Mark = 98

Enter Mark = 76

Enter Mark = 28

Enter Mark = 46

Enter Mark = 15

1. Tamil Mark = 45

2. English Mark = 98

3. Physics Mark = 76

4. Chemistry Mark = 28

5. Comp. Science Mark = 46

6. Maths Mark = 15

Total Marks = 308

Program 4: Python program to read prices of 5 items in a list and then display sum of all the prices, product of all the prices and find the average

items=[]

prod=1

for i in range(5):

print ("Enter price for item { } : ".format(i+1))

p=int(input())

items.append(p)

for j in range(len(items)):

print("Price for item { } = Rs. { }".format(j+1,items[j]))

prod = prod * items[j]

print("Sum of all prices = Rs.", sum(items))

print("Product of all prices = Rs.", prod)

print("Average of all prices = Rs.",sum(items)/len(items))

Output:

Enter price for item 1 :

5

Enter price for item 2 :

10

Enter price for item 3 :

15

Enter price for item 4 :

20

Enter price for item 5 :

25

Price for item 1 = Rs. 5

Price for item 2 = Rs. 10

Price for item 3 = Rs. 15

Price for item 4 = Rs. 20

Price for item 5 = Rs. 25

Sum of all prices = Rs. 75

Product of all prices = Rs. 375000

Average of all prices = Rs. 15.0

Program 5: Python program to count the number of employees earning more than 1 lakh per annum. The monthly salaries of n number of employees are given

count=0

n=int(input("Enter no. of employees: "))

print("No. of Employees",n)

salary=[]

for i in range(n):

print("Enter Monthly Salary of Employee { } Rs.: ".format(i+1))

s=int(input())

salary.append(s)

for j in range(len(salary)):

annual_salary = salary[j] * 12

print ("Annual Salary of Employee { } is:Rs. { }".format(j+1,annual_salary))

if annual_salary >= 100000:

count = count + 1

print("{ } Employees out of { } employees are earning more than Rs. 1 Lakh per annum".

format(count, n))

Output:

Enter no. of employees: 5

No. of Employees 5

Enter Monthly Salary of Employee 1 Rs.:

3000

Enter Monthly Salary of Employee 2 Rs.:

9500

Enter Monthly Salary of Employee 3 Rs.:

12500

Enter Monthly Salary of Employee 4 Rs.:

5750

Enter Monthly Salary of Employee 5 Rs.:

8000

Annual Salary of Employee 1 is:Rs. 36000

Annual Salary of Employee 2 is:Rs. 114000

Annual Salary of Employee 3 is:Rs. 150000

Annual Salary of Employee 4 is:Rs. 69000

Annual Salary of Employee 5 is:Rs. 96000

2 Employees out of 5 employees are earning more than Rs. 1 Lakh per annum

Program 6: Write a program to create a list of numbers in the range 1 to 10. Then delete all the even numbers from the list and print the final list.

Num = []

for x in range(1,11):

Num.append(x)

print("The list of numbers from 1 to 10 = ", Num)

for index, i in enumerate(Num):

if(i%2==0):

del Num[index]

print("The list after deleting even numbers = ", Num)

Output

The list of numbers from 1 to 10 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] The list after deleting even numbers = [1, 3, 5, 7, 9]

Program 7: Write a program to generate in the Fibonacci series and store it in a list. Then find the sum of all values.

a=-1

b=1

n=int(input("Enter no. of terms: "))

i=0

sum=0

Fibo=[]

while i<n:

s = a + b

Fibo.append(s)

sum+=s

a = b

b = s

i+=1

print("Fibonacci series upto "+ str(n) +" terms is : " + str(Fibo))

print("The sum of Fibonacci series: ",sum)

Output

Enter no. of terms: 10

Fibonacci series upto 10 terms is : [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

The sum of Fibonacci series: 88

 

 

Tags : Python , 12th Computer Science : Chapter 9 : Python Modularity and OOPS : Lists, Tuples, Sets And Dictionary
Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
12th Computer Science : Chapter 9 : Python Modularity and OOPS : Lists, Tuples, Sets And Dictionary : Introduction to List | Python


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.