Skip to main content

List in Python

A list is an ordered set of values, where each value is identified by an index. The values that make up a list are called its elements. Lists are similar to strings, which are ordered sets of characters, except that the elements of a list can have any type.
Lists are the most versatile sequence type. The elements of a list can be any object, and lists are mutable - they can be changed. Elements can be reassigned or removed, and new elements can be inserted.
List is one of the simplest and most important data structures in Python.
Lists are enclosed in square brackets [ ] and each item is separated by a comma.
Lists are collections of items where each item in the list has an assigned index value.
A list is mutable, meaning you can change its contents.
Lists are very flexible and have many built-in control functions
Creating Lists
To create a list, place a (possibly empty) comma-separated list of objects or expressions in square brackets. For example, the following initializes a list with three elements:
L1= [10, 20, 30]
L2=["spam", "bungee", "swallow"]
The lists L1 contains 3 integer elements and the list L2 contains 3 strings.
The elements of lists can be any objects (even expressions, functions or other lists!), and they need not all be the same type. The example below, for instance, contains a list with different data tape.
L=[10,2.3,3+4j,'djd',3*4]
The following list contains a string, a float, an integer, and another list. A list within another list is said to be nested.
L=["hello", 2.0, 5, [10, 20]]
The nested list can be used to represent a matrix.
A=[[1,2,3],[4,5,6],[7,8,9]]
will create a nested list A( which can be used as a matrix)
print A[0] will print [1,2,3]
print A[1][2] will print 6.

The following command will create empty lists
L1=list() # using built in list function
L2=[]
The range command generate a list of integers
>>range(1,5)
[1,2,3,4]
Using other lists also we can create a new list
L2=L1[:] # here L2 is created as copy of L1
L2=L1[2:6] # here L2 is created with 2,3,4 and 5 elements of L1.
Python supports a concept called "list comprehensions". It can be used to construct lists in a very natural, easy way, like a mathematician is used to do.
This will create a list of even numbers less than 100.
[ i for i in range(100) if i%2==0]
More Examples of List Comprehensions
>>> S = [x**2 for x in range(10)]
>>> V = [2**i for i in range(13)]
>>> M = [x for x in S if x % 2 == 0]
>>> print S; print V; print M
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096]
[0, 4, 16, 36, 64]
Accessing List Elements
To access the i'th element of a list, use the list name followed by the index in square brackets.
Note that lists in Python are zero-indexed, so the first element is at index 0, the second is at index 1, and so on. Negative indices wrap around, so -1 is the last element, -2 is the penultimate element, etc
Example:
L = [10, 20, [60, 70, 80], 30]
>>>L[2]     >>>L[1]    >>>L[-1]   >>>L[-3] >>>L[5/2]        >>>L[2][2]
[60,70,80]       [20]               [30]           [20]         [60,70,80]      80
Note: We can use an expression for index. But only integer values are permitted for index.
Slice operator works on list also. We know that a slice of a list is its sub-list.
>>>L[1:4]                   >>>L[2:]                     >>>L[:3]                     >>>L[::2]
[20,[60,70,80],30]       [[60,70,80],30]            [10,20,[60,70,80]]       [10,[60,70,80]]
List Traversal
We can also access elements of a list by using looping constructs while and for. "for" is more efficient. If we are using "while" we should also know the length of the list, which can be found by the sequence function len().
Example:                              
i=0                                          for i in L:
while i <len(L):                                print i,
print L[i],
i+=1
List Operations
The + operation concatenate lists

>>>A=[10,20,30]
>>>B=[40,50,60,70,80]
>>>A+B
[10,20,30, 40,50,60,70,80]
The * operator repeats a list given number of times.
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
Slicing operator[::] can be used to extract elements from a list
>>>B=[40,50,60,70,80]
>>>B[2:5]
[60,70,80]
Membership of an element in a list can be tested with in and not in
>>>B=[40,50,60,70,80]
>>>40 in B
True
>>>100 in B
False
>>>100 not in B
True
Changing/Modifying List elements
The list is a mutable sequence. It means that we can change the list elements.
To change the i’th element simply assign a new value to the i’th index
>>>L=[10,20,30,40]
>>>L[2]=100 # will set the 3rd element to 100 in the list L.
>>>L
[10,20,100,40]
>>>L[-1]=200 # will change the last element to 200.
>>>L
[10,20,100,200]
We can also use slicing to change more than one value using another list
>>>L[2:4]=[111,222]
>>>L
[10,20,111,222]
Adding Elements to the List
One way to add elements to the list is by using concatenation (+ operator).We can concatenate an element to a list in the beginning or at the end.
>>>L=[20,30,40]
>>>L+[50]
[20,30,40,50]
>>>[10]+L
[10,20,30,40]
We can also use the append() method to add elements at the end of the list.
>>>L=[10,20,30]
>>>L.append(40)
>>>L.append(50)
>>>L
[10,20,30,40,50]
We can also use insert() method to insert element at a particular position.
>>>L.insert(0,5) # will insert 5 before index 0
>>>L
[5,10,20,30,40,50]
>>>L.insert(-1,100)
>>>L
[5,10,20,30,40,100,50]
The list can be extended with more elements by extend() method
>>>L=[10,20,30]
>>>L.extend([40,50,60])
>>>L
[10,20,30,40,50,60]
Deleting Elements from a List
pop() method can be used to take the last element from a list. When the list is empty it will return index error.
>>>L=[10,20,30]
>>>L.pop()
30
>>>L
[10,20]
The method remove() will remove the specified element from the list. If the element is not present in the list, it will return value error.
>>>L=[10,20,30]
>>>L.remove(20)
>>>L
[10,30]
The del() function can also be used to delete an element from a list, if you don’t know the element to delete. It uses the index to delete the element.
>>>L=[10,20,30,40]
>>>del(L[1])
>>>del(L[-1])
>>>L
[10,30]
We can use slicing with del() to delete more elements
>>>L=[10,20,30,40]
>>>del(L[1:3])
>>>L
[10,40]
>>>L=[10,20,30,40]
>>>del(L[-1:-3:-1])
>>>L
[10,20]
Searching and Sorting
The index() method can be used to find the position of an element in a list. If the element is not present it will return a value error.
Note: we can use ‘in’ to check whether an element is present in the list or not.
>>>L=[10,20,30,40]
>>>L.index(30)
2
The count() method returns number of occurrences of an element in a list.
>>>L=[10,20,30,30,40]
>>>L.count(30)
2
>>>L.count(100)
0
The sort() function can be used to sort the list in ascending or descending order
>>> L=[10, -30, 40]
>>> L.sort()
>>>L
[-30, 10, 40]
>>> L.sort(reverse=True)
>>> L
[40, 10, -30]
When you sort a list containing strings, ASCII ordering is used
>>> L=["binu","anu","biju"]
>>> L.sort()
>>> L
['anu', 'biju', 'binu']
>>> L.sort(reverse=True)
>>> L
['binu', 'biju', 'anu']
We can also specify a function as key so that the list will be sorted based on that function. The following example sort the list elements based on the length of the string.
>>> L=['binu','anu','bimal']
>>> L.sort(key=len)
>>> L
['anu', 'binu', 'bimal']
>>> L=['binu','anu','bimal']
>>> L.sort(key=len,reverse=True)
>>> L
['bimal', 'binu', 'anu']
It is noted that when you use sort() method the original list is modified. We can use sorted() method to create a new sorted list without changing the original.
L=['bimal', 'binu', 'anu']
>>> sorted(L)
['anu', 'bimal', 'binu']
>>> sorted(L,reverse=True)
['binu', 'bimal', 'anu']
>>> sorted(L,reverse=True,key=len)
['bimal', 'binu', 'anu']
Other useful functions
len() function will return the number of elements in the list.
>>> L=[10,20,30,40]
>>> len(L)
4
min() and max() will return the minimum and maximum element
>>> L=[10,20,30,40]
>>> min(L)
10
>>> max(L)
40
sum() function will return the sum of the elements.
>>> L=[10,20,30,40]
>>> sum(L)
100
We can find average of the list elements L by sum(L)/len(L)
>>> sum(L)/len(L)
25
Strings and Lists
We can use split method in the string module to split a string and create a list of words.
Now you can process these list using the list functions.
>>> s="this is a test"
>>> w=s.split(' ')
>>>w
['this', 'is', 'a', 'test']
>>> "_".join(w) # words are joined with ‘_’ character.
'this_is_a_test'
Aliasing and Cloning List
When we assign one list to another variable it creates an alias of the list object.It means that it will not create a separate list object.
>>>a=[10,20,30]
>>>b=a # this will create an alias
We can test the object id using the function id() to test that they refer to the same object.
>>> id(a)
35033696
>>> id(b) # note that the ids are same
35033696
>>>a[2]=100
>>>b
[10,20,100]
If you want to clone a list , ie; if we need a copy of the list, slicing can be used. This will create a new object. Note that the ids of the objects are different.
>>> b=a[::]
>>> b
[10, 20, 30]
>>> a
[10, 20, 30]
>>> id(a)
35033696
>>> id(b)
35034096
Sample Programs
Program to read list of names and sort the list in alphabetical order.( university question)
n=input("Enter the number of names....")
names=[]
print "Enter {} names".format(n)
for i in range(n):
   nam=raw_input()
   names.append(nam)
names.sort()
print "names in alphabetical order"
for nam in names:
    print nam
Program to find the sum of all even numbers in a group of n numbers entered by the user. (university question)
n=input("Enter the number of elements...")
print "Enter the {} elements".format(n)
l=[] # creating an empty list
for i in range(n):
    x=input()
    l.append(x)
s=0
for i in range(n):
    if l[i]%2==0:
        s=s+l[i]
print "Sum of all even numbers",s
Note:you can also enter a list by using square brackets.
Eg: L=input(“Enter a list..”)
[10,20,30] # give the input like a list.
This will create a list L.
Program to read a string and remove the given words from the string.
s=raw_input("Enter the string....")
wr=raw_input("Enter the word to remove....")
wrds=s.split(" ")
ns=""
for w in wrds:
    if w!=wr:
        ns=ns+" "+w
print "new string...",ns
Program to read list of numbers and find the median
#We can find median by sorting the list and then take the middle element. If the list contains even number of elements take the average of the two middle elements.
n=input("Enter how many numbers....")
print "Enter {} numbers....".format(n)
ls=[]
for i in range(n):
   x=input()
   ls.append(x)
ls.sort()
print ls
mid=n/2
if n%2==1:
   print "Median",ls[mid]
else:
   print "median",(ls[mid]+ls[mid-1])/2.0
Program to remove all duplicate elements from a list
lst=[]
n=input("enter how many numbers..")
print "Enter elements..."
for i in range(n):
    x=input()
    lst.append(x)

nlst=[]
for x in lst:
    if x not in nlst:
        nlst.append(x)
print "new list after removing duplicates"
print nlst
The simple way to remove duplicate elements from a list is to convert into a set and then convert back to list
lst=[]
n=input("enter how many numbers..")
print "Enter elements..."
for i in range(n):
    x=input()
    lst.append(x)
nlst=list(set(lst))
print "new list after removing duplicates"
print nlst

This program will completely remove duplicate elements without keeping any copy.
l=input('Enter list with duplicates...')
nl=list(set(l)) # list with only one copy
nlwd=[] # new list without duplicates
for i in nl:
   if l.count(i)==1: #non duplicate element
      nlwd.append(i)
print "New list after removing duplicates completely..."
print nlwd
Write a menu driven program to store the students details(rno,name,mark) as a list of tuples.The menu has the following options ( university question)
add-adding students details
remove-remove the details by giving roll number
search-search and display the details by giving roll number
max-display the details of the students with highest mark
stud=[]
while True:
    print "1.add\n2.remove\n3.search\n4.max\n5.exit"
    op=input("Enter option....")
    if op==1:
        print "Enter the students details.."
        rno=input("enter roll number...")
        name=raw_input("enter name..")
        mark=input("enter mark..")
        stud.append((rno,name,mark))
        print stud
    if op==2:
        rno=input("Enter the rollnumber to remove")
        stud=filter(lambda x:x[0]!=rno,stud)
        print stud
    if op==3:
        rno=input("Enter the rollnumber to search")
        print filter(lambda x:x[0]==rno,stud)
    if op==4:
        stud=sorted(stud,key=lambda x:x[2],reverse=True)
        print stud[0]
    if op==5:
        print "Bye"
        break
Write a Python program to read a list consisting of integers, floating point numbers and strings. Separate them into different lists depending on the data(university question)
print "Enter 10 list entries of different data types(int/float/string)..."
l=[]
il=[]
fl=[]
sl=[]
for i in range(10):
    x=input()
    l.append(x)
for i in l:
  if type(i)==int:
    il.append(i)
  if type(i)==str:
    sl.append(i)
  if type(i)==float:
    fl.append(i)

 print "Integer list"
print il
print "Float list"
print fl
print "String List"
print sl

Write a Python program to read list of positive integers and separate the prime and composite numbers (university question)
def prime(n):
        flag=1
        for i in range(2,n/2+1):
                if n%i==0:
                        flag=0
                        break
        return flag    
pl=[]
cl=[]
l=[]
n=input("Enter n..")
print "Enter the numbers.."
for i in range(n):
    x=input()
    l.append(x)
for i in l:
  if prime(i):
          pl.append(i)
  else:
          cl.append(i)
print "prime list"
print pl
print "composite list"
print cl  
Now you can try the following programs using Lists
1.Read list of numbers and check whether the given element in found in the list. If found display the positions else display the message element is not found.( index() method only find the first occurrence. use a loop)
2.Count the number of occurrences of an element in a list. ( use count() method or use a loop)
3.Read a list and remove the first and last element .Create a new list( use del(), pop() and slicing)
4. Write program to read list of names and print the names in sorted order.(use sort())
5. Read list of numbers and print the list in reverse sorted order.(use sort())
6. Program to find the sum of all even numbers in a group of ‘n’ numbers entered by the user. (university question)
7. Write a Python program to count the number of –ve terms and zeros in a given set of n numbers (university question)
8. Write a Python program to input a list of  ‘n’ numbers. Calculate and display the average of ‘n’ numbers. Also display cube of each value in the list.(university question)
9.Read a list of ‘n’ numbers and find the smallest and largest among them.(use min() and max())
10.Find the second largest and second smallest element from a list.( use sort().min(),max())
11.Read list of numbers and find the median.(refer example)
12.Read list of numbers and find the standard deviation.
13.Find the duplicate elements from a list.( use count())
14.Read a string and print the words in alphabetical order ( use split() and sort())
15.Read a string and print each words and its length.Also print number of words.(use split() and len())
16.Read a string and remove all occurrence of a word ( use split() and join())
17.Read a string and replace all occurrence of a word with another (use split() and join())
18.Read a string and sort the words according to the length of the words.
19.Read list of names and print the sorted list in uppercase letters.
20.Remove all duplicate elements from a list.( refer example)
21.Read a string and remove all duplicate words.
22.Read a list and remove the duplicate elements completely. ( refer example)
23.Read a list and create a new list from this after removing all occurrences of a given element.
24.Remove the smallest and largest element from the list.
25.Students marks of an exam is stored as a list. Create two list of marks from this.( passed and failed, less than 50% is failed). Also find the number of passed and failed students.Average marks of passed students,Top scorer and lowest mark scorer.
26.write a python program to input a sentence and find the number of words in the sentence and print the words in uppercase.Also print the number of question marks(?), periods(.) and commas(,) present in the string. ( university question)
27.Write a python program to input a list of 'n' numbers.Calculate and display the sum of cubes each value in the list. ( university question)
28. Write a Python program to read a list consisting of integers, floating point numbers and strings. Separate them into different lists depending on the data(university question)
29.write a Python program to read list of positive integers and separate the prime and composite numbers

Matrix Implementation using Lists

We can implement matrix operation using list. Matrix operation can be implemented using nested list. List inside another list is called nested list.

Consider 2x2 matrix A A=[[1,2],[3,4]]

We can write a nested for loop to iterate and print the list in matrix form
for i in range(2):
   for j in range(2):
       print A[i][j],” “,
   print
Nested for loop can also be used to read the mxn matrix elements as a list.Here nested list is initialized with 0 after reading the number of rows (m)and number of columns(n) before reading the elements.
The following program will read a m x n matrix as list and print it in the matrix form.
m=input("Enter the number of rows..")
n=input("Enter the number of columns..")
A=[[0 for c in range(n)]for r in range(m)] #initializing a nested list
print "Enter the elements of each row line by line.."
for r in range(m):
  for c in range(n):
     A[r][c]=input()
print "The Matrix is....."
for r in range(m):
   for c in range(n):
        print A[r][c]," ",
print
The following program will find the sum of two matrix A+B=C
m=input("Enter the number of rows..")
n=input("Enter the number of columns..")
A=[[0 for c in range(n)]for r in range(m)]
B=[[0 for c in range(n)]for r in range(m)]
C=[[0 for c in range(n)]for r in range(m)]
print "Enter the elements of each row of matrix A line by line.."
for r in range(m):
    for c in range(n):
        A[r][c]=input()
print "Enter the elements of each row of matrix B line by line.."
for r in range(m):
    for c in range(n):
        B[r][c]=input()
for r in range(m):
    for c in range(n):
        C[r][c]=A[r][c]+B[r][c]
print "The Matrix A is....."     
for r in range(m):
    for c in range(n):
        print A[r][c]," ",
    print      
print "The Matrix B is....."     
for r in range(m):
    for c in range(n):
        print B[r][c]," ",
    print
print "The sum C=A+B...."
for r in range(m):
    for c in range(n):
        print C[r][c]," ",
    print
The above program is written efficiently using functions
def readmatrix(X):
   for r in range(m):
      for c in range(n):
           X[r][c]=input()
def printmatrix(X):
   for r in range(m):
      for c in range(n):
          print X[r][c]," ",
   print
def findsum(A,B,C):
   for r in range(m):
      for c in range(n):
          C[r][c]=A[r][c]+B[r][c]

m=input("Enter the number of rows..")
n=input("Enter the number of columns..")
A=[[0 for c in range(n)]for r in range(m)]
B=[[0 for c in range(n)]for r in range(m)]
C=[[0 for c in range(n)]for r in range(m)]
print "Enter the elements of each row of matrix A line by line.."
readmatrix(A)
print "Enter the elements of each row of matrix B line by line.."
readmatrix(B)
findsum(A,B,C)
print "The Matrix A is....."
printmatrix(A)
print "The Matrix B is....."
printmatrix(B)
print "The sum C=A+B...."
printmatrix(C)
The following program will multiply two square matrix A*B=Cdef readmatrix(X):
  for r in range(m):
      for c in range(n):
        X[r][c]=input()
def printmatrix(X):
   for r in range(m):
        for c in range(n):
              print X[r][c]," ",
    print
def findprod(A,B,C):
   for i in range(m):
       for j in range(n):
            for k in range(n):
                C[i][j]=C[i][j]+A[i][k]*B[k][j]
m=input("Enter the number of rows..")
n=input("Enter the number of columns..")
A=[[0 for c in range(n)]for r in range(m)]
B=[[0 for c in range(n)]for r in range(m)]
C=[[0 for c in range(n)]for r in range(m)]
print "Enter the elements of each row of matrix A line by line.."
readmatrix(A)
print "Enter the elements of each row of matrix B line by line.."
readmatrix(B)
findprod(A,B,C)
print "The Matrix A is....."
printmatrix(A)
print "The Matrix B is....."
printmatrix(B)
print "The Product C=A*B...."
printmatrix(C)
Read a matrix and find the sum of each row and each column (uq)m=input("Enter the number of rows..")
n=input("Enter the number of columns..")
A=[[0 for c in range(n)]for r in range(m)] #initializing a nested list
print "Enter the elements of each row line by line.."
for r in range(m):
   for c in range(n):
         A[r][c]=input()
print "The Matrix with row sum and column sum is....."
for r in range(m):
     rs=0
    for c in range(n):
         rs=rs+A[r][c]
         print A[r][c]," ",
    print rs
print
for c in range(n):
    cs=0
    for r in range(m):
         cs=cs+A[r][c]
    print cs," ",
Try the following matrix programs using nested lists
1.Find the sum of two matrices.
2.Find the difference of two matrices.
3.Find the product of two matrices.
4.Find the transpose of a matrix.
5.Print the diagonal elements and find the trace(sum of diagonal elements).
6.Print the row sum and column sum.

Comments

  1. Pretty Post! Thank you so much for sharing this good content, it was so nice to read and useful to improve my knowledge as an updated one, keep blogging.

    Python Certification Training in Electronic City

    ReplyDelete

Post a Comment

Popular posts from this blog

Classes and Objects in Python

Python is an object-oriented programming language, which means that it provides features that support object-oriented programming. The basic components of object oriented programming are classes and objects. A Class is a blue print to create an object. It provides the definition of basic attributes and functions of objects. Object is a running instance of the class having the identity(name), properties( values) and behaviors(functions). The Object oriented program thus consist of object definitions (classes) and most of the computations and functions are mentioned as operations on the object. Each object definition corresponds to some object or concept in the real world, and the functions that operate on these object correspond to the ways real-world objects interact. We have learned objects of string, list, tuple etc…and used the properties and functionalities of these objects which are built into the Python. Now we are going to create our own(user defined) objects. Th

Identifiers,Variables and Keywords

Identifiers An identifier is a name given to entities like variables,functions,class, functions etc. It helps to differentiate one entity from another. Rules for writing identifiers 1.Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore _.  Names like myClass, var_1 and print_this_to_screen, all are valid example. 2.An identifier cannot start with a digit. 1variable is invalid, but variable1 is a valid name. 3.Keywords cannot be used as identifiers. Eg: global = 1 is invalid 4.We cannot use special symbols like !, @, #, $, % etc. in our identifier. a@=0 is invalid 5.An identifier can be of any length. Things to Remember Python is a case-sensitive language. This means, Variable and variable are not the same. Always give the identifiers a name that makes sense. While c = 10 is a valid name, writing count=10 would make more sense, and it would be easier to figure out what it represents when you look at your code after

Files in Python , Exception handling

While a program is running, its data is in main memory. When the program ends, or the computer shuts down, data in memory disappears. To store data permanently, you have to put it in a file. Files are usually stored on a secondary storage device(hard disk, pen drive, DVD,CD etc).  When there are a large number of files, they are often organized into directories (also called “folders”). Each file is identified by a unique name, or a combination of a file name and a directory name.  By reading and writing files, programs can exchange information with each other and generate printable formats like PDF. Working with files is a lot like working with books. To use a book, you have to open it. When you’re done, you have to close it. While the book is open, you can either write in it or read from it. In either case, you know where you are in the book. Most of the time, you read the whole book in its natural order, but you can also skip around. All of this applies to files as well.