Sunday 11 January 2015

My Python Notes-->(List & List Comprehension)

What is a list ?

List is a collection of similar numbers , strings or both.
List is a container which hold elements in a particular order.
   

Creating a list 

To create an empty list
 lst = []

To create a list of number from 1 to 5
num =[1,2,3,4,5]

To create a list of alphabets
alpha = ['a','b','c','d','e']

To create a list  of words     
seasons = ['Summer','Winter','Autumn','Spring']

To create a list of word containing number
pythonReleases = ['python3.4.2','python 2.7.0','python 2.7.9']

To create a list within a list
bigList =[[], 
                [1,2,3,4,5],
                ['a','b','c','d','e'],
                ['Summer','Winter','Autumn','Spring'],
                ['python3.4.2','python 2.7.0','python 2.7.9']
               ]



Note-----Like string elements we can access each and every list element using the index value.

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

To access the 1st element
firstElement = alpha[0]

To access the last element
lastElement = alpha[-1]

Example 1

Python List Methods

List in python is a class.

Note:List can also be created by using list()--method.
Eg ---list_name = list()




.append(value) ---adds "value" to the end of the list.

Lets consider an empty list
lst = []
To add an element to the list
lst.append(1)



.pop()---remove element from the list

pop()--by default remove the last element

seasons = ['summer', 'winter', 'autumn', 'spring']
seasons.pop()---will remove 'spring' from the list "seasons".

We can remove a particular element based on the index
Syntax-------seasons.pop([index])
seasons.pop(1)--- will remove 'winter' from the list "seasons".

.insert()---Now if we need to insert a value at a particular index we can use insert.

List are Mutable

browsers = ['IE6','Chrome','firefox','UC']

Now the element at index 2 is firefox,  if we what to insert "phantomjs" at index 2 we can do it using insert().
Syntax-------browsers.insert([index],value)


.remove()---remove an element based on its value and not based on the index value.

pythonContainters  = ['list','sets','tuple','dictionary']

pythonContainters.remove('list')---will remove 'list' value from the list "pythonContainers".

If the element to be remove if not found , an error is throw.
Lets try to remove 'jude' from the list 'pythonContainters'
  .count()---count the number of time an element occurs in a given list
lets us create two list
lst = [1,2,1,4]
lst_char = ['a','a','d','e']
Note:List can store duplicate values.

Python String Methods

.joint()---is a string method we can use it to join a list of strings

words = ['my','name' ,'is ','jude ']
If we want to join the above list with a space between each list element

' '.join(words)

If we want to join the above list with '_' between each list element
'_'.join(words)

.split()---is a string method we can convert string into list.

string ="my name is jude"
' '.split(string)-----> will convert the string to a list.

names = "jude job james john joseph"
'j'.split(names)---->will return a list contain word without the letter "j".


Looping over List

For--loop--over single list

Syntax:
            for name in iterable:
                  statements
                  ........
                  ......
          iterable---produces a stream of values
         and assign each value to name.
         for each value of name the statements are executed.

names = ['john','jude','mary','james','joseph']
I want to print the name from the names list using for--loop

for name in names:
      print(name)
Output
Now using for--loop we can print the data and index value as well

enumerate()---help us to make useful pair.


for index,name in enumerate(names):
      print("names[%d] = %s "%(index,name))

 For--loop--over two list

zip()---makes a pair-wise loop
words = ['apple','boy','cat','dog']
alphabets = ['a','b','c','d']

Python List Comprehension

 List-Comprehension allow us to built sequence from other sequence.

Example 2.1--write a program which takes a list and return a new list with square of each element from the given input list(Without list - Comprehension)



Example 2.2--A function which takes a list and return a new list with square of each element from the given list.(Using list-Comprehension)


Output --  for ex2.1.py and ex2.2.py

List-Comprehension which filter input sequence based on a certain condition.
Note:Condition are optional.

Example 3.1--A function which takes a input sequence of number and return a sequence of numbers greater than zero.(Without List Comprehension)


Example 3.2--A function which takes a input sequence of number and return a sequence of numbers
greater than Zero( Using List-Comprehension)

Output -- is for both ex3.1.py and ex3.2.py

 List-Comprehension with multiple conditions

Example 4.1--A function which takes a input sequence of number and return a sequence of even-numbers.(WithOut list-Comprehension)

Example 4.2--With List Comprehension Output for ex4.1.py & ex4.2.py

List-Comprehension for two loops
Example 5.1--Working with two loops Example 5.2--Using list-Comprehension
Output
Example 6.1 Let us combine two list, string list and  number list(WithOut Comprehension)
Note we can convert an integer into a string using str()--method.
Example 6.2---Repeat example 6.1 Using List Comprehension
Output

 Example 7--generating an unity matrix with List Comprehension
A unity matrix =[
                             [1,0,0]
                             [0,1,0]
                             [0,0,1]
                          ]

Example 8--generate a diagonal matrix whose diagonal element are equal to the row number
diagonal_matrix =[
                               [1,0,0,]
                               [0,2,0],
                               [0,0,3]
                              ]

Example 9--generate a diagonal matrix whose diagonal element are equal to square of the row number.
square_matrix =[
                               [1,0,0]
                               [0,4,0]
                               [0,0,9]
                              ]


1 comment: