python basics
Map()
Takes a function as a 1st argument and applies it to each of the elements of its 2nd argument, an iterable. Examples of iterables are strings, lists, and tuples.
1 | list(map(lambda x: x.capitalize(), ['math', 'poem', 'drawing'])) |
The output:
1 | ['Math', 'Poem', 'Drawing'] |
example of passing multiple iterators to map() using lambda
1 | num1 = [1, 2, 3] |
2 | num2 = [4, 5, 6] |
3 | |
4 | sum = map(lambda n1, n2: n1+n2, num1, num2) |
5 | print(list(sum)) |
The output:
1 | [5, 7, 9] |
Filter()
Takes a predicate as a 1st argument and an iterable as a 2nd argument. It builds an iterator containing all the elements of the initial collections that satisfies the predicate function.
1 | list(filter(lambda x: x%3 == 0, range(13))) |
The output:
1 | [0, 3, 6, 9, 12] |
Reduce()
- Call a function with the first 2 items from the sequence and return the result.
- Call the function again with the result obtained in step 1 and the next value in the sequence. Such process repeats until the end.
1 | import functools |
2 | lis = [ 1 , 3, 5, 6, 2, ] |
3 | print (functools.reduce(lambda a,b : a+b,lis)) |
4 | print (functools.reduce(lambda a,b : a if a > b else b,lis)) |
The output:
1 | 17 |
2 | 6 |
Sorted()
1 | sorted(iterable, key=None, reverse=False) |
- iterable - A sequence (string, tuple, list) or collection (set, dictionary, frozen set) or any other iterator.
- key - A function that serves as a key for the sort comparison.
1 | # List |
2 | x = ['j', 'u', 'p', 'y', 't', 'e', 'r'] |
3 | print (sorted(x)) |
4 | |
5 | # Tuple |
6 | x = ('j', 'u', 'p', 'y', 't', 'e', 'r') |
7 | print (sorted(x)) |
8 | |
9 | # String-sorted based on ASCII translations |
10 | x = "jupyter" |
11 | print (sorted(x)) |
12 | |
13 | # Dictionary |
14 | x = {'j':1, 'u':2, 'p':3, 'y':4, 't':5, 'e':6, 'r':7} |
15 | print (sorted(x)) |
16 | |
17 | # Set |
18 | x = {'j', 'u', 'p', 'y', 't', 'e', 'r'} |
19 | print (sorted(x)) |
20 | |
21 | # Frozen Set |
22 | # remember that sets can't contain mutable objects, but sets are mutable |
23 | fruits = set(["apple", "orange", "watermelon"]) |
24 | fruits.add("strawberry") |
25 | print (fruits) |
26 | # but frozenset is immutable |
27 | x = frozenset(('j', 'u', 'p', 'y', 't', 'e', 'r')) |
28 | print (sorted(x)) |
29 | # when using dictionary as an iterable for a frozen set, it only takes key of the dictionary to create the set. |
30 | stu = {"name": "Yoyo", "age": 18, "sex": "female"} |
31 | info_stu = frozenset(stu) |
32 | print(info_stu) |
The output:
1 | ['e', 'j', 'p', 'r', 't', 'u', 'y'] |
2 | ['e', 'j', 'p', 'r', 't', 'u', 'y'] |
3 | ['e', 'j', 'p', 'r', 't', 'u', 'y'] |
4 | ['e', 'j', 'p', 'r', 't', 'u', 'y'] |
5 | ['e', 'j', 'p', 'r', 't', 'u', 'y'] |
6 | {'orange', 'strawberry', 'apple', 'watermelon'} |
7 | ['e', 'j', 'p', 'r', 't', 'u', 'y'] |
8 | frozenset({'sex', 'age', 'name'}) |
1 | sorted("He has a friend named amiau".split(), key=str.lower) |
The output:
1 | ['a', 'amiau', 'friend', 'has', 'He', 'named'] |
1 | holiday_tuples = [ |
2 | ('Bern', 'A', 10), |
3 | ('Ann', 'B', 20), |
4 | ('Jim', 'A', 6), |
5 | ] |
6 | sorted(holiday_tuples, key=lambda stu: stu[2]) |
The output:
1 | [('Jim', 'A', 6), ('Bern', 'A', 10), ('Ann', 'B', 20)] |
1 | def remain(x): |
2 | return x % 3 |
3 | |
4 | S = [10, 9, 23, 20] |
5 | |
6 | sorted(S, key = remain) |
The output:
1 | [9, 10, 23, 20] |
zip()
map the similar index of multiple containers so that they can be used just using as single entity.
1 | name = [ "Manjeet", "Nikhil", "Shambhavi", "Astha" ] |
2 | roll_no = [ 4, 1, 3, 2 ] |
3 | marks = [ 40, 50, 60, 70 ] |
4 | |
5 | # using zip() to map values |
6 | mapped = zip(name, roll_no, marks) |
7 | |
8 | # converting values to print as list |
9 | mapped = list(mapped) |
10 | |
11 | # printing resultant values |
12 | print ("The zipped result is : ",end="") |
13 | print (mapped) |
14 | |
15 | print("\n") |
16 | |
17 | # unzipping values |
18 | namz, roll_noz, marksz = zip(*mapped) |
19 | |
20 | print ("The unzipped result: \n",end="") |
21 | |
22 | # printing initial lists |
23 | print ("The name list is : ",end="") |
24 | print (namz) |
25 | |
26 | print ("The roll_no list is : ",end="") |
27 | print (roll_noz) |
28 | |
29 | print ("The marks list is : ",end="") |
30 | print (marksz) |
The output:
1 | The zipped result is : [('Manjeet', 4, 40), ('Nikhil', 1, 50), ('Shambhavi', 3, 60), ('Astha', 2, 70)] |
2 | |
3 | |
4 | The unzipped result: |
5 | The name list is : ('Manjeet', 'Nikhil', 'Shambhavi', 'Astha') |
6 | The roll_no list is : (4, 1, 3, 2) |
7 | The marks list is : (40, 50, 60, 70) |
Another example:
1 | # initializing list of players. |
2 | players = [ "Sachin", "Sehwag", "Gambhir", "Dravid", "Raina" ] |
3 | |
4 | # initializing their scores |
5 | scores = [100, 15, 17, 28, 43 ] |
6 | |
7 | # printing players and scores. |
8 | for pl, sc in zip(players, scores): |
9 | print ("Player : %s Score : %d" %(pl, sc)) |
The output:
1 | Player : Sachin Score : 100 |
2 | Player : Sehwag Score : 15 |
3 | Player : Gambhir Score : 17 |
4 | Player : Dravid Score : 28 |
5 | Player : Raina Score : 43 |
If we do not pass any parameter, zip() returns an empty iterator
If a single iterable is passed, zip() returns an iterator of tuples with each tuple having only one element.
If multiple iterables are passed, zip() returns an iterator of tuples with each tuple having elements from all the iterables.
Suppose, two iterables are passed to zip(); one iterable containing three and other containing five elements. Then, the returned iterator will contain three tuples. It’s because iterator stops when the shortest iterable is exhausted.
1 | numbersList = [1, 2, 3] |
2 | str_list = ['one', 'two'] |
3 | numbers_tuple = ('ONE', 'TWO', 'THREE', 'FOUR') |
4 | # Notice, the size of numbersList and numbers_tuple is different |
5 | result0 = zip() |
6 | result = zip(numbersList, numbers_tuple) |
7 | # Converting to set |
8 | result_set0 = set(result0) |
9 | print(result_set0) |
10 | result_set = set(result) |
11 | print(result_set) |
12 | result = zip(numbersList, str_list, numbers_tuple) |
13 | # Converting to set |
14 | result_set = set(result) |
15 | print(result_set) |
The output:
1 | set() |
2 | {(3, 'THREE'), (1, 'ONE'), (2, 'TWO')} |
3 | {(2, 'two', 'TWO'), (1, 'one', 'ONE')} |