33.List functions/methods, searching and sorting, object identity

Useful functions with List

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
del() function can be also used for deleting element(s)
>>>del(L[1])
>>>L
[10,30,40]
del() function can be used to delete multiple element(s)
>>> l=[4,5,6,7,8,9]
>>> del(l[0:3])
>>> l
[7, 8, 9]

Python List Methods

Methods that are available with list objects in Python programming are tabulated below.
They are accessed as list.method(). 

append() - Add an element to the end of the list
extend() - Add all elements of a list to the another list
insert() - Insert an item at the defined index
remove() - Removes an item from the list
pop() - Removes and returns an element at the given index or last element
clear() - Removes all items from the list
index() - Returns the index of the first matched item
count() - Returns the count of the number of items passed as an argument
sort() - Sort items in a list in ascending order
reverse() -Reverse the order of items in the list
copy() - Returns a shallow copy of the list

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
>>>L.index(50)
Traceback (most recent call last):
  File "<pyshell#44>", line 1, in <module>
    L.index(50)
ValueError: 50 is not in list
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]
This can also be done by sorting the list and then reversing it
>>>L.sort()
>>>L.reverse()
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']

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 or use the copy() function. 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

Equality: Object Identity and Structural Equivalence
Occasionally, programmers need to see whether two variables refer to the exact same object or to different objects. For example, you might want to determine whether one variable is an alias for another. The == operator returns True if the variables are aliases for the same object. Unfortunately, == also returns True if the contents of two different objects are the same. The first relation is called object identity, whereas the second relation is called structural equivalence. The == operator has no way of distinguishing between these two types of relations.

Python’s is operator can be used to test for object identity. It returns True if the two operands refer to the exact same object, and it returns False if the operands refer to distinct objects (even if they are structurally equivalent). The next session shows the difference between == and is, and Figure below depicts the objects in question.

>>> first = [20, 30, 40]
>>> second = first
>>> third = list(first) # Or first[:]
>>> first == second
True
>>> first == third
True
>>> first is second
True
>>> first is third
False


all()


The syntax of the all() function is: 
all(iterable)


The all() function takes a single parameter: iterable - any iterable (list, tuple, dictionary, etc.) which contains the elements


The all() function returns True if all elements in the given iterable are true. If not, it returns False

all() Return Value

all() function returns: True - If all elements in an iterable are true
False - If any element in an iterable is false
When                                         Return Value
All values are true                         True
All values are false                         False
One value is true (others are false) False
One value is false (others are true) False
Empty Iterable                                 True

any()
The any() function returns True if any element of an iterable is True. If not, it returns False. 
The syntax of the any) function is:  
any(iterable)
 

The any() function returns a boolean value: True if at least one element of an iterable is true
False if all elements are false or if an iterable is empty
 
Condition                                         Return 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


map() function


The map() function executes a specified function for each item in an iterable. The item is sent to the function as a parameter.

Syntax
map(function, iterables)

function : The function to execute for each item
iterable: A sequence, collection or an iterator object. You can send as many iterables as you like, just make sure the function has one parameter for each iterable.

Example-1:
def myfunc(n):
    return len(n)

x = map(myfunc, ['apple', 'banana', 'cherry'])
print(list(x))

[5,6,6]

Example-2:
def myfunc(a, b):
  return a + ":" +  b

x = map(myfunc, ('apple', 'banana', 'cherry'), ('orange', 'lemon', 'pineapple'))
print(list(x))

['apple:orange', 'banana:lemon', 'cherry:pineapple']


filter() function

The filter() function returns an iterator where the items are filtered through a function to test if the item is accepted or not.

Syntax
filter(function, iterable)

function:A Function to be run for each item in the 
terableiterable:The iterable to be filtered

Example:

ages = [5, 12, 17, 18, 24, 32]

def myFunc(x):
  if x < 18:
    return False
  else:
    return True

adults = filter(myFunc, ages)
print(list(adults))  

[18, 24, 32]


enumerate()

Often, when dealing with iterators, we also need to keep a count of iterations. Python eases the programmers’ task by providing a built-in function enumerate() for this task. The enumerate () method adds a counter to an iterable and returns it in the form of an enumerating object. This enumerated object can then be used directly for loops or converted into a list of tuples using the list() function.


Syntax: 
enumerate(iterable, start=0)

Iterable: any object that supports iteration
Start: the index value from which the counter is to be started, by default it is 0

Return: Returns an iterator with index and element pairs from the original iterable


Example-1


Here, we are using the enumerate() function with both a list and a string. Creating enumerate objects for each and displaying their return types. It also shows how to change the starting index for enumeration when applied to a string, resulting in index-element pairs for the list and string

L = ["eat", "sleep", "repeat"]
S = "geek"

# creating enumerate objects
obj1 = enumerate(L)
obj2 = enumerate(S)

print ("Return type:", type(obj1))
print (list(enumerate(L)))

# changing start index to 2 from 0
print (list(enumerate(S, 2)))

Output:
Return type: <class 'enumerate'>
[(0, 'eat'), (1, 'sleep'), (2, 'repeat')]
[(2, 'g'), (3, 'e'), (4, 'e'), (5, 'k')]


Example-2 Using Enumerate Object in Loops

enumerate() is used with a list . It first prints tuples of index and element pairs. Then it changes the starting index while printing them together

L = ["eat", "sleep", "repeat"]

# printing the tuples in object directly
for ele in enumerate(L):
print (ele)

# changing index and printing separately
for count, ele in enumerate(L, 100):
print (count, ele)

Output
(0, 'eat')
(1, 'sleep')
(2, 'repeat')

100 eat
101 sleep
102 repeat

Comments

Popular posts from this blog

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

46.Classes and Objects in Python- Accessors and mutators

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