32.Lists in Python-List operations,creating,accessing, modifying, adding and deleting elements,list comprehensions

List is one of the simplest and most important data structures 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 , meaning you can change its contents. Elements can be reassigned or removed, and new elements can be inserted.Lists are enclosed in square brackets [ ] and each item is separated by a comma.

Lists are very flexible and have many built-in control functions.

Here are some real-world examples of lists
  • A shopping list for the grocery store
  • A to-do list
  • A recipe, which is a list of instructions....etc
1.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 a nested list.
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 and list() function can be used to generate a list
>>list(range(1,5))
[1,2,3,4]

Using other lists also we can create a new list.We crate a new list L2 from L1
L2=L1 # creates an alias only
L2=L1[:] # here L2 is created as copy of L1
L2=L1[2:6] # here L2 is created with 2,3,4 and 5th elements of L1.

List comprehensions
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.
List comprehension is an elegant and concise way to create a new list from an existing list in Python.

A list comprehension consists of an expression followed by for statement inside square brackets.
Here is an example to make a list with each item being increasing power of 2.
pow2 = [2 ** x for x in range(10)] 
print(pow2)

Output
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]

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 = [math.sqrt(i) for i in range(5)]
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]
[0.0, 1.0, 1.4142135623730951, 1.7320508075688772, 2.0]
[0, 4, 16, 36, 64]

we can also use user defined function
def f(x):
    y=x**2
    return y
l=[f(x) for x in range(10)]
print(l)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]


2.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]


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

Slicing operator[::] can be used to extract elements from a list
B=[40,50,60,70,80]
B[2:5]
[60,70,80]


3.Access elements from a list

There are various ways in which we can access the elements of a list.

List Index
We can use the index operator [] to access an item in a list. In Python, indices start at 0. So, a list having 5 elements will have an index from 0 to 4.

Trying to access indexes other than these will raise an IndexError. The index must be an integer. We can't use float or other types, this will result in TypeError.

Nested lists are accessed using nested indexing.Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on.
 
>>>L = [10, 20, [60, 70, 80], 30]
>>>L[2] 
[60,70,80]
 >>>L[1] 
[20]
 >>>L[-1] 
 [30]
 >>>L[-3] 
 [20]
>>>L[5//2] 
[60,70,80]
 >>>L[2][2]
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 = [10, 20, [60, 70, 80], 30]
>>>L[1:4]
[20,[60,70,80],30]
>>>L[2:]
[[60,70,80],30]
>>>L[:3]
[10,20,[60,70,80]]
>>>L[::2]
[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: 
for i in L:
    print (i)                         

i=0 
while i <len(L): 
    print(L[i])
    i+=1
4.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]

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

6.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]
>>L.pop(0)
10
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 clear() function will remove all elements from the list.
>>>L.clear()
>>>L
[]
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]
>>>del(L) # will delete the list object

Comments

Popular posts from this blog

Python For Machine Learning - CST 283 - KTU Minor Notes- Dr Binu V P

KTU Python for machine learning Sample Question Paper and Answer Key Dec 2020

46.Classes and Objects in Python- Accessors and mutators