Lists, Tuples, Dictionaries, Looping, Lambda, Filter, Reduce and Map
In [1]:
listA = [1,"This is a list", "c" , "kong"]
listb=[1,2,3]
listA.extend(listb) #List.extend(L) -> Extend the list by appending all in the given list L
print (listA)
listA.append(4) #List.append(x) -> adds an item to the end of the list
print (listA)
listA.insert(3,4)
print (listA)
listA.remove(4)
print
a = [66.25, 333, 333, 1, 1234.5]
print (a)
print (a.count(333))
print (a.index(333))
a.reverse()
print (a)
a.sort()
print (a)
In [4]:
#the Delete Statement
b = [-1, 1, 66.25, 333, 333, 1234.5]
print (b)
del b[0]
print (b)
del b[2:4]
print (b)
del b[2:5]
print (b)
In [2]:
# Using Lists as Stacks [LIFO] - Last In First Out
stack = [5,6,7]
print (stack)
stack.append (8)
print (stack)
stack.pop()
print (stack)
In [24]:
from collections import deque
queue = deque (["Eric", "John", "Michael"])
print (queue)
queue.append("Terry")
print (queue)
queue.append ("Adam")
print (queue)
queue.pop()
print (queue)
queue.popleft()
print (queue)
In [25]:
basket = ['apple', 'orange', 'apple', 'pear']
fruit = set(basket)
print (fruit)
In [27]:
# Tuples --> A number of values separated by commas. Immutable.
# A tuple is a sequence of immutable Python objects.
# Tuples are sequences, just like lists.
# The differences between tuples and lists are,
# the tuples cannot be changed unlike lists and
# tuples use parentheses, whereas lists use square brackets.
# To write a tuple containing a single value you have to include a comma,
# even though there is only one value −
# tup1 = (50,); #singleton
t = (56789, 98765, 'hello!')
print (t[0])
print (t[1])
In [13]:
# Dictionaries
# Each key is separated from its value by a colon (:),
# the items are separated by commas,
# and the whole thing is enclosed in curly braces.
# An empty dictionary without any items is written with just two curly braces, like this: {}
tel = {'jack':4098, 'sape':4139}
tel['guido'] = 4127 #adding content in dictionary
print (tel)
print (tel ['jack'])
del tel['sape'] # for deleting content
tel ['irv'] = 4127
print (tel)
print (tel.keys()) #to check the key strings where different values are allocated
'guido' in tel # to check whether a string is present in the dictionary or not
Out[13]:
In [17]:
# Looping Techniques
# Iteritems() --> for retrieving key and values through a dictionary
# {} --> Curly parenthesis for defining dictionarie. When this dictionary is printed, the order will be random
knights = {'gallahad': 'the pure', 'emporer' : 'fighter', 'robin':'the brave' }
for a, b in knights.items(): #Python 2 - iteritems() and Python3 - items()
print (a, b) #use any variable to retreive and print the output like here we used a and b
friends = {'soham': 'chowdhury', 'sivaram' : 'kanagaraj', 'prasanna':'balan' }
for a, b in friends.items(): #Python 2 - iteritems() and Python3 - items()
print ("\n",a, b) #use any variable to retreive and print the output like here we used a and b
In [20]:
# Looping Techniques
# Enumerate() --> for the position index and values in a sequence
for i, v in enumerate(['tic', 'tac', 'toe']): # i - index no. and v - values corresponding
print (i,v)
m = ['tic', 'tac', 'toe']
for i, v in enumerate(m):
print ("\n",i,v)
In [21]:
# Zip
# Zip() --> for looping over two or more sequences
questions = ['name', 'quest', 'favorite color']
answers = ['Soham', 'Python', 'Orange.']
for q, a in zip(questions, answers):
print ('What is your {0}? It is {1}'.format(q,a))
In [22]:
# Comparisons
# Operators “in” and “not in” can be used to see-
# -if an item exists in a sequence
# Comparisons can be chained
# This tests whether a is less than b and that b equals c
a=3
b=4
c=4
print (a < b == c)
In [23]:
# List Programming Tools
# Lambda Operator
# The lambda operator or lambda function is a way to create small anonymous functions,
# i.e. functions without a name.
# These functions are throw-away functions,
# i.e. they are just needed where they have been created.
# Lambda functions are mainly used in combination with the functions filter(), map() and reduce().
# The lambda feature was added to Python due to the demand from Lisp programmers.
volume = lambda l,b,h: l*b*h
print (volume(3,4,5))
In [27]:
# Filter(function, sequence)
# - Returns a sequence consisting of the items from
# the sequence for which function(item) is true
def f(y):return y%2!=0 and y%3!=0
d=filter(f, range(2,50))
print(list(d))
# using lambda operator
q = lambda p: p%2!=0 and p%3!=0
v=filter(q, range(2,50))
print(list(v))
#another example
fib = [0,1,1,2,3,5,8,13,21,34,55]
result = filter(lambda z: z % 2, fib)
print (list(result))
result = filter(lambda z: z % 2 == 0, fib)
print (list(result))
In [35]:
# Map Function
# Map(function, sequence)
# - Calls function(item) for each of the sequence’s items
def cube(x): return x**3
n=map (cube, range(1,11))
print(list(n))
#Using Lambda operator
w = lambda x: x**3
f=map(w, range(1,21))
print (list(f))
def fahrenheit(T):
return ((float(9)/5)*T + 32)
def celsius(T):
return (float(5)/9)*(T-32)
temp = (36.5, 37, 37.5,39)
F = map(fahrenheit, temp)
print (list(F))
C = map(celsius, temp)
print (list(C))
Celsius = [39.2, 36.5, 37.3, 37.8]
Fahrenheit = map(lambda x: (float(9)/5)*x + 32, Celsius)
print (list(Fahrenheit))
C = map(lambda x: (float(5)/9)*(x-32), temp)
print (list(C))
#Example
a = [1,2,3,4]
b = [17,12,11,10]
c = [-1,-4,5,9]
print(list(map(lambda x,y:x+y, a,b)))
print(list(map(lambda x,y,z:x+y+z, a,b,c)))
print(list(map(lambda x,y,z:x+y-z, a,b,c)))
In [2]:
# Reduce function
# Reduce(function, sequence)
# - Returns a single value constructed by calling
# the binary function (function)
from functools import reduce #In python 3, reduce function is moved to functools which we need to call first before running
def add(x,y): return (x+y)
b=reduce(add, range(1,11)) # always remember, range(1,11) means starting from 1 till 11 in which 11 is not included.
print(b) # hence, b is addition of 1 to 10
# using lambda operator
e = lambda a,b : a+b
k=reduce(e, range(1,11))
print(k)
# https://www.python-course.eu/lambda.php
a= reduce(lambda x,y: x+y, [47,11,42,13])
print (a)
f = lambda a,b: a if (a > b) else b
b = reduce(f, [47,11,42,102,13])
print (b)
c = reduce(lambda x, y: x+y, range(1,101))
print (c)
Comments
Post a Comment