My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more
Advanced Python Made Easy - Part 1

Advanced Python Made Easy - Part 1

Naina's photo
Naina
·Nov 27, 2021·

2 min read

image.png

In this part we will see some advanced python constructs that will help you write efficient code, improve code readability and performance. Let's dive in!

1. Lambda Expression

Lambda is used to create small anonymous functions using "lambda" keyword and can be used wherever function objects are needed. It can any number of arguments but only one expression.

Syntax :

lambda argument(s): expression

Implementation -

#lambda arguments : expression
#A lambda function that adds 10 to the number passed in as an argument, and print the result
x = lambda a, b, c : a * b + c
print(x(5, 6, 8))

Output -

38

It can be used inside another function.

Implementation -

def cal(n):
    return lambda t : t ** n
var = cal(3)
print(var(12))

Output -

1728

2. Function Arguments

If you want to pass multiple arguments or keywords arguments to a function then use args and *kwargs .

Symbols used -

  1. *args - Non-Keyword Arguments

  2. **kwargs - Keyword Arguments

Implementation (*args - Non-Keyword Arguments) -

def addNum(*add_numbers):
    result=2+add_numbers[2]+add_numbers[6]
    return result
#call the function
addNum(5,3,19,46,66,26,10)

Output-

31

Implementation (**kwargs - Keyword Arguments) -

def my_function(**legend):
    print("His last name is " + legend["lname"])
my_function(fname = "Steve", lname = "Jobs")

Output -

His last name is Jobs

3. Function Annotations

Python 3.0 added function annotation which can be of great help when type checking since python supports dynamic typing. They collect information about the type pf parameters used and the return type of the function. They can be used with single parameters, function arguments, nested functions, decorators etc.

Implementation -

def cal(x:int, y: float, z: int) -> float: print(x * y + z)
cal(5,6.5,7)

Output-

39.5

4. OrderedDict

OrderedDict is one of the high performance container datatypes and a subclass of dict object. It maintains the order in which the keys are inserted. In case of deletion or re-insertion of the key, the order is maintained.

Implementation -

print ('Ordered Dict')
dict2 = collections.OrderedDict()
dict2['a'] = 'A'
dict2['b'] = 'B'
dict2['c'] = 'C'
for key, value in dict2.items():
    print (key, value)

Output-

Ordered Dict
a A
b B
c C

Post written by : Naina ( Find me : naina0412.medium.com)

Read More :

https://medium.com/coders-mojo/quick-recap-60-days-of-data-science-and-machine-learning-5676932bd39b?sk=484b33cbb82a3d1d0d3427f87a04a3c4