Python Tutorial

Showing posts with label keyword. Show all posts
Showing posts with label keyword. Show all posts

Wednesday, November 11, 2015

map keyword

Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items.


All source code available on github
intArray = [2, 3, 4, 6, 5, 7]
strArray = ['2', '3', '4', '6', '5', '7']

# square all elements of array
print map(lambda x:x**2, intArray)

# convert string array to int array
print map(int, strArray)

a = [1, 2, 3]
b = [4, 5, 6]

# sum two array elements  by index
print map(lambda x, y : x+y, a, b)


Output:
[4, 9, 16, 36, 25, 49]
[2, 3, 4, 6, 5, 7]
[5, 7, 9]

Thursday, December 12, 2013

Python enumerate

enumerate returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence.
a = ["Python","easy"]

for i, n in enumerate(a):
    print i, n


Output:
0 Python
1 easy

Thursday, June 13, 2013

lambda keyword

Python supports an interesting syntex creation of anonymous functions at runtime, using a construct called "lambda" .

f = lambda x: 2*x + 5
print f(3)
print f(5)

f = lambda x : x%2 and "Odd" or "Even"
print "5 is",f(5)
print "10 is",f(10)

Output:
11
15
5 is Odd
10 is Even