Course Discount

Search

Python Programming Filter

How To Use Python Lambda Functions

Modern-day programming languages like Python and other programming languages like C, C#, and Java have added lambda functions to their syntax to increase the functionality of the languages.Python Lambdas are anonymous functions which are small and restricted and come without an identifier.Lambda Calculus is a universal model of computation which was formalized by Alonzo Church in the 1930s. In simple terms, it is a formal system in mathematical logic that is based on pure abstraction and can encode any Turing Machine.The two models of computations— lambda calculus and Turing machines can be translated into one another. This equivalence is known as the Church-Turing Hypothesis. However, the lambda calculus is Turing complete and does not keep any state, unlike the Turing machine.The Turing machine has led to the discovery of the imperative style of programming. This type of approach requires managing states and comprises of programming with statements which drive the program in steps, using a comprehensive and detailed instruction format. Languages like C, Fortran, or Python uses this type of programming technique.On the other hand, the lambda philosophy focuses on data abstraction, transformation, and purity. Their approach is declarative in nature and functional languages like Haskell, Lisp, or Erlang directly inherit them.However, functional features are also a part of the imperative programming style, especially with the implementation of lambda functions in Python or Java.Although Python is not a functional language, some functional features like map(), filter(), reduce(), and the lambda operator were added to Python in the year 1994. To learn more about such features, join our Python certification course.What are Lambdas in Python?Lambda expressions or lambda forms are used to create anonymous functions. Let us first see an identity function. It is an identity relation or identity map that returns the same argument that was originally provided as input. This is a standard Python definition defined using the def keyword:>>> def identity(z): ...    return zOn the other hand, a Python lambda function can have any number of parameters and is written in a single line of code. However, the body of the function can have only one expression.An example of a Python lambda construct:>>> lambda z: zThe expression above comprises of three essential parts:The lambda keyword.The parameters.The function body.Another example of a lambda function with an argument:>>> (lambda z: z + 1)(5) 6Here, the argument and the function are surrounded by parentheses. The function adds 1 to the argument.Since lambda function is an expression, you are allowed to name it whatever you want. Let us perform reduction to compute the value of an expression by naming the lambda function:>>> add = lambda x: x + 1 >>> add(5) 6We can also declare multi-argument function by listing arguments and separating them with commas ( , )  but without using parentheses:>>> name = lambda first_name, last_name: f'The full name is {first.title()} {last.title()}' >>> name('Alex', 'Pandian') 'The full name is Alex Pandian'Here, the function add takes two arguments and returns a string by interpolating the two parameters first_name and last_name.What are Anonymous Functions in Python?A function without a name is known as an anonymous function in Python. It is created with the help of the keyword lambda.An example of an anonymous function with two arguments:>>> lambda a, b: a + bHere, the function has two arguments x and y and is defined using lambda and is not bound to any variable. The function accepts the two arguments and returns their sum.However, you can invoke the same function using an interactive interpreter-only feature of Python via the underscore(_):>>> _(4, 5) 9In the interactive interpreter, the single underscore(_) is bound to the last expression evaluated which means it points to the last lambda function.The functions which take one or more arguments and returns the result are known as higher-order functions.A lambda function can be a higher-order function:>>> higher_order_function = lambda x, f1: x + f1(x) >>> higher_order_function(3, lambda x: x * x) 12 >>> higher_order_function(3, lambda x: x + 3) 9The higher-order functions are considered as built-in functions in the Python Standard Library. Some of the examples are filter(), map(), reduce() or key functions like min(), max(), sort() or sorted().Python Lambdas vs Regular FunctionsA Lambda function might be considered a function with a syntax within a programming language which makes the language “sweeter” for human use. It is created to make things easier to read and express.However, there are a number of precise differences between the regular functions and Python lambdas. The following section highlights them all.A. Difference in FunctionsIn fundamental terms, there is almost no difference between a regular function with a single return line and a lambda function. However, let us check what difference it would make while we write it in code:>>> import dis >>> sub = lambda a, b: a + b >>> type(sub) <class 'function'> >>> dis.dis(sub)   1           0 LOAD_FAST                0 (x)               2 LOAD_FAST                1 (y)               4 BINARY_ADD               6 RETURN_VALUE >>> sub <function <lambda> at 0x000001E47F3EC268>The dis module subjects a readable version of the Python bytecode generated by the compiler, which in turn displays the low-level instructions used by the Python interpreter.Let us try the same with a regular function:>>> import dis >>> def sub(x,y): return a + b >>> type(sub) <class 'function'> >>> dis.dis(sub)   1           0 LOAD_FAST                0 (x)               2 LOAD_FAST                1 (y)               4 BINARY_ADD               6 RETURN_VALUE >>> sub <function <lambda> at 0x000001E47F3EC268>You can see the Python bytecode is similar in both cases. However, what differs is the style of naming. With def, the function is named as sub whereas lambda is used in case of Python built-in function.B. Difference in TracebackAn example of exception raising using lambda:>>> divide_by_zero = lambda a: a / 0 >>> divide_by_zero(2) Traceback (most recent call last):     File "<stdin>", line 1, in <module>     File "<stdin>", line 1, in <lambda> ZeroDivisionError: division by zeroWhen you’re using a lambda expression, the traceback of an exception identifies only the function, resulting in the exception as <lambda>.On the other hand, when you’re using a regular function, the traceback provides the name of the function in particular:>>> def divide_by_zero(a): return a / 0 >>> divide_by_zero(2) Traceback (most recent call last):     File "<stdin>", line 1, in <module>     File "<stdin>", line 1, in divide_by_zero ZeroDivisionError: division by zeroThe traceback returns the function name divide_by_zero.C. Difference in SyntaxA lambda expression differs in syntax from a normal function in a number of ways: Expressions and StatementsA lambda function can contain only expressions and cannot include any statements. It will raise a SyntaxError upon using statements like return, assert or raise.Let us see an example of using an assert statement in a lambda function:>>> (lambda a: assert a == )(2) SyntaxError: invalid syntaxThe interpreter raises an error while parsing the code since assert is not a valid keyword in a lambda expression. Single ExpressionIn a Python lambda expression, you can distribute the expression across several lines using parentheses or a multi-line string. But the function will still remain as a single expression:>>> (lambda a: ... (a % 2 and 'odd' or 'even'))(5) 'odd'The lambda expression above spreads over two lines but still remains a single expression which evaluates a number and results into odd or even depending upon the argument. AnnotationsYou can use Python type hints and type checking when you’re using normal functions:def name(first_name: str, last_name: str) -> str:     return f'{first_name.title()} {last_name.title()}'If there are any errors with the function name, it can be caught using packages like mypy or pyre. On the other hand, if you’re using a lambda expression, a SyntaxError will be raised:>>> lambda first_name: str, last_name: str: first_name.title() + " " + last_name.title() -> str  File "<stdin>", line 1     lambda first: str, last: str: first.title() + " " + last.title() -> str SyntaxError: invalid syntax IIFEImmediately Invoked Function Execution or IIFE is a JavaScript function that gets executed as soon as it is defined. However, you cannot use it outside the Python Interpreter.An example of such is:>>> (lambda a, b: a + b)(4,6) 10The IIFE is mainly used to pass the definition of a Python function into a higher-order function like map(), filter() or reduce().D. Difference in ArgumentsPython supports different ways of passing arguments in a lambda expression just like regular functions. Some of which are as follows:Named arguments.Variable list of arguments.Positional arguments.Variable list of keyword arguments.Keyword only arguments.An example to illustrate different ways of passing arguments in a lambda function:>>> (lambda a, b, c: a + b + c)(1, 2, 3) 6 >>> (lambda a, b, c=3: a + b + c)(1, 2) 6 >>> (lambda a, b, c=3: a + b +c)(1, b=2) 6 >>> (lambda *arg: sum(arg))(1,2,3) 6 >>> (lambda **kwarg: sum(kwarg.values()))(number_one=1, number_two=2, number_three=3) 6 >>> (lambda a, *, b=0, c=0: a + b + c)(1, b=2, c=3) 6E. Difference in DecoratorsA decorator is a function that accepts another function and allows adding a behavior to a function or class. Its syntax is @decorator which is written before a function.An example of a decorator is:def decorator(a):     def wrap(*arguments):         print(f"Calling function '{a.__name__}'")         return a(arguments)     return wrap @decorator def decorated_func(x):     print(f"With argument '{x}'")If we invoke decorated_func(“Hello World”), the output will be as follows:Calling function 'decorated_func' With argument 'Hello World'The function decorated_func() prints With argument 'Hello World', but the decorator adds a behavior and also prints  Calling function 'decorated_func'An example of applying decorator in lambda function is mentioned below:# Defining a decorator def trace(a):   def wrap(*arg, **kwarg): print(f"[TRACE] func: {f.__name__}, args: {arg}, kwarg: {kwarg}") return a(*arg, **kwarg)   return wrap # Applying decorator to the function @trace def add(t):     return t + 2 # Calling the decorated function add(3) # Applying decorator to a lambda function print((trace(lambda y: y ** 2))(3))If we execute the following code, we’ll get the following output:[TRACE] func: add, arg: (3,), kwarg: {} [TRACE] func: <lambda>, arg: (3,), kwarg: {} 9The function add is decorated with @trace and invoked. The lambda function gets implemented to the decorator. The lambda function name is <lambda> and the regular function is add.F. Difference in ClosuresA closure is a function object that remembers values and is bound to a specified value in the enclosing scope of that function. In simple words, closure is a record that stores a function and defines the environment in which they run.Both lambda functions and regular functions can be implemented as closures.An example to show a closure construct with a regular function:def outer_function(a):     b = 4     def inner_function(c):         print(f"a = {a}, b = {b}, c = {c}")         return a + b + c     return inner_function     for i in range(5):     closure = outer_function(i)     print(f"closure({i+5}) = {closure(i+5)}")inner_function() is a nested function that is being returned by outer_function(). The nested function evaluates the sum of three arguments. The outer_function() is invoked 5 times in a for loop resulting in the output:x = 0, y = 4, z = 5 closure(5) = 9 x = 1, y = 4, z = 6 closure(6) = 11 x = 2, y = 4, z = 7 closure(7) = 13 x = 3, y = 4, z = 8 closure(5) = 15 x = 4, y = 4, z = 4 closure(5) = 017An example to show closure using a Python lambda function:def outer_function(a):     b = 4     return lambda c: a + b + c   for i in range(5):     closure = outer_function(i)     print(f"closure({i+5}) = {closure(i+5)}")The output of the above code will be:closure(5) = 9 closure(6) = 11 closure(7) = 13 closure(7) = 15 closure(7) = 17In both situations, the normal function and the lambda function behaves precisely similar.G. Difference in Evaluation TimeA lambda function’s behavior as a closure may be counter-intuitive, especially while working with loops.  Using a regular function:>>> def wrap(x): ...    def f(): ...        print(x) ...    return f ... >>> numbers = 'one', 'two', 'three' >>> f1 = [] >>> for x in numbers: ...    f1.append(wrap(x)) ... >>> for f in f1: ...    f() ... one two threeWhen the function f1 gets appended to the list, x is evaluated at definition time.Let us implement the same using lambda function:>>> numbers = 'one', 'two', 'three' >>> f1 = [] >>> for x in numbers: ...    f1.append(lambda: print(x)) ... >>> for f in f1: ...    f() ... three three threeSince n is a free variable bound at runtime  when we invoke the function f, an unexpected error occurs printing three all the time.However, to get rid of this situation, you can assign the free variable during definition time:>>> numbers = 'one', 'two', 'three' >>> f1 = [] >>> for x in numbers: ...    f1.append(lambda x=x: print(x)) ...  >>> for f in f1: ...    f() ... one two threeThe lambda argument is initialized with a default value. So, when the function is invoked, the default value x set at definition time is used.Testing LambdasYou can test Python lambdas similarly like regular functions with the help of two modules— unittest and doctest.unittestTesting Python lambda function using unittest:import unittest add = lambda x: x + 2 class Lambda_Testing(unittest.TestCase):     def test_add1(self):         self.assertEqual(add(2), 4)     def test_add2(self):         self.assertEqual(add(2.2), 4.2)     def test_add3(self):         # Should fail         self.assertEqual(add(3), 6) if __name__ == '__main__':     unittest.main(verbosity=2)The function Lambda_Testing tests three methods, each implemented as a lambda function. After execution, the Python file produces the following output:$ python lambda_unittest.py test_add3 (__main__.Lambda_Testing) ... FAIL test_add1 (__main__.Lambda_Testing) ... ok test_add2 (__main__.Lambda_Testing) ... ok ====================================================================== FAIL: test_add_three (__main__.Lambda.Testing) ---------------------------------------------------------------------- Traceback (most recent call last):   File "lambda_unittest.py", line 18, in test_add_three     self.assertEqual(add3(3), 6) AssertionError: 5 != 6 ---------------------------------------------------------------------- Ran 3 tests in 0.001s FAILED (failures=1)There are two successful test cases and one failure for test_add3. However, if we change the expected result from 6 to 5, the Lambda_Testing will be satisfied for all tests.doctestThe doctest module tests Python lambdas by extracting Python code from docstring:add = lambda a: a + 2 add.__doc__ = """Add 2 to a number.     >>> add(2)     4     >>> add(2.2)     4.2     >>> add(3) # Should fail     6     """ if __name__ == '__main__':     import doctest     doctest.testmod(verbose=True)You can execute the code above using doctest.testmod(), the output will be:$ python lambda_doctest.py Trying:     add(2) Expecting:     4 ok Trying:     add(2.2) Expecting:     4.2 ok Trying:     add(3) # Should fail Expecting:     6 ********************************************************************** File "lambda_doctest.py", line 16, in __main__.add Failed example:     add(3) # Should fail Expected:     6 Got:     5 1 items had no tests:     __main__ ********************************************************************** 1 items had failures:    1 of   3 in __main__.add 3 tests in 2 items. 2 passed and 1 failed. ***Test Failed*** 1 failures.Here, the failure of the test result is also because of the same test failures explained above in the execution of test cases. Although  it is possible to use docstrings for lambda functions, Python recommends using docstrings for regular functions rather than lambda functions.Where should you not use Lambda Expressions?You can simply say that if there is a situation where lambda expressions are not supported, normal functions would be more suitable in such places.However, there might be situations when you need to avoid lambda expressions in your code:When it doesn’t follow the Python Style Guide ( PEP 8 ).When it is difficult to read and interpret.When it doesn’t support readability.Exception Raising An example of raising an exception in a Python lambda:>>> def throw_except(excpt): raise excpt >>> (lambda: throw_except(Exception('Exception is raised')))() Traceback (most recent call last):     File "<stdin>", line 1, in <module>     File "<stdin>", line 1, in <lambda>     File "<stdin>", line 1, in throw Exception: Something bad happenedThough there are some really clever ways of raising an exception in Python lambda, it is always suggested to use a normal function. This is because a statement is never correct in syntax in the body of a Python lambda function.Cryptic StyleLambda functions are brief in nature, because of which it might be difficult to read. An example of a bad writing style lambda  expression:>>> (lambda _: list(map(lambda _: _ // 2, _)))([1,2,3,4,5,6,7,8,9,10]) [0, 1, 1, 2, 2, 3, 3, 4, 4, 5]Let us modify this lambda code by naming the variables:>>> (lambda some_list: list(map(lambda a: a // 2, list)))([1,2,3,4,5,6,7,8,9,10]) [0, 1, 1, 2, 2, 3, 3, 4, 4, 5]The code is still difficult to read and understand. However, if we execute the same code using a regular function by distributing the logic across several lines, it would greatly impact the readability of the code:>>> def divide(list):       divide = lambda a: a // 2       return map(divide, list) >>> list(divide([1,2,3,4,5,6,7,8,9,10]))) [0, 1, 1, 2, 2, 3, 3, 4, 4, 5]Though this method is not the best, it surely enhances the readability of the code in comparison to the lambda expressions.Python ClassAn example of a Python class using lambda:class Car:     """Car with methods as lambda functions."""     def __init__(s, brand, year):         s.brand = brand         s.year = year     brand = property(lambda s: getattr(s, '_brand'),                     lambda s, value: setattr(s, '_brand', value))     year = property(lambda s: getattr(s, '_year'),                     lambda s, value: setattr(s, '_year', value))     __str__ = lambda s: f'{s.brand} {s.year}'  # 1: error E731     honk = lambda s: print('Honk!')     # 2: error E731If you use a style guide tool like flake8 for checking the code above, it will result in following errors for __str__ and honk:E731 do not assign a lambda expression, use a defSince multiple strings like '_brand and'_year' are used, the properties that are difficult to read are inclined to errors.Ultimately, considering a general rule, you should have a preference for regular functions instead of lambda functions in the context of Python programming.Where should you use lambda expressions?Lambdas provide a shortened syntax for writing functions, which return a single expression. Since Python supports functional programming, lambdas are one of the most common use cases in such a paradigm of programming. Lambdas allow a fine way to pass functions as arguments to another function by creating a one-time function and passing it as a parameter.Let us discuss some situations where using lambdas are very appropriate and also suggested by Python.Functional Constructs Built-in functions like map(), filter(), and functools.reduce(), found in the functools module, are often used along with lambda expressions.Three examples of those functions along with lambda expressions:>>> list(map(lambda x: x.upper(), ['alex', 'bob', 'charles'])) ['ALEX', 'BOB', 'CHARLES'] >>> list(filter(lambda x: 'o' in x, ['alex', 'bob', 'charles'])) ['BOB'] >>> from functools import reduce >>> reduce(lambda acc, x: f'{acc} | {x}', ['alex', 'bob', 'charles']) 'alex | bob | charles'There are other functional constructs which are alternatives to these constructs and are considered more Pythonic in nature.Key FunctionsPython key functions are higher-order functions that directly determine the algorithm driven by the key function. They accept a named parameter known as key, which in turn takes a lambda function.Some of the most commonly used key functions are sort(), sorted, min(), max(), nlargest() and nsmallest().Let us sort a list of IDs using sorted(), in which each ID is a concatenated string of string id and a  number. To sort the list of IDs with the help of the corresponding number associated, we’ll assign lambda to the key argument:>>> ids = ['ID1', 'ID9', 'ID11', 'ID3', 'ID25', 'ID200'] >>> print(sorted(ids))#Sorting ['ID1', 'ID9', 'ID11', 'ID3', 'ID25', 'ID200'] >>> sorted_ids = sorted(ids, key=lambda x: int(x[2:]))#Integer sorting >>> print(sorted_ids) ['ID1', 'ID9', 'ID11', 'ID3', 'ID25', 'ID200']UI FrameworksSome of the UI frameworks that use lambda expressions for their UI events are Tkinter, wxPython or .NET Windows Forms.An example of a Tkinter program using lambda:import tkinter as t import sys window = t.Tk() window.grid_columnconfigure(0, weight=1) window.title("Lambda Calculus") window.geometry("500x200") label = t.Label(window, text="HELLO WORLD") label.grid(column=0, row=0) button = t.Button(     window,     text="Reverse the string",     command=lambda: label.configure(text=label.cget("text")[::-1]), ) button.grid(column=0, row=1) window.mainloop()When the Reverse button is clicked, an event gets fired that triggers the lambda, which in turn changes the label from HELLO WORLD  to DLROW OLLEH.Though lambda can handle firing events, it is always recommended to use a normal function instead as the lambda ends up being self-contained in a shortcode structure.The Python InterpreterPython lambdas are considered as bliss when you use it inside the Python Interpreter. In comparison to regular functions, creating a single-line lambda function to look into some code is much easier. The lambdas in interpreter are just like scrap paper that is useless after being used once and are later thrown away.The timeit moduletimeit is a Python module that is used to time small fragments of Python code. In simple words, it measures the evaluation time of small code snippets.An example of timeit.timeit() being called directly:>>> from timeit import timeit >>> timeit("factorial(100)", "from math import factorial", number = 5) 1.799199999652501e-05A NameError exception would be raised if the full context of the statement is not passed as a string. So the environment should be set up that is required by the main function to be timed.However a  cleaner and more readable solution to the above code is by using a lambda function:>>> from math import factorial >>> timeit(lambda: factorial(100), number=5) 1.799199999652501e-05Although the lambda version takes less execution time, the string version has a benefit of executing the functions again.What are the alternatives of lambda expressions?The higher-order functions like map(), filter(), and functools.reduce() can be used in place of lambdas by changing the form with lists and generators.Using map() map() takes two arguments— a function and an iterable like string, lists or tuples. It executes the function object for each element and returns a modified list of elements.An example to illustrate map() with lambda by transforming a string of integers into its capitalized form:>>> list(map(lambda x: x.capitalize(), ['alex', 'bob', 'charles'])) ['Alex', 'Bob', 'Charles']list() should be invoked so that the iterator gets converted into the modified list which can be shown as output in the Python Interpreter.Using filter()filter() accepts two arguments— a boolean-valued function and an iterable. It is an excellent way to filter out all elements of a sequence for only those which returns True.An example of filter() with lambda which returns all odd numbers from a list:my_list = [5, 10, 21, 95, 51, 69, 72, 22, 70, 99] final_list = list(filter(lambda x: (x%2 != 0) , my_list)) print(final_list) [5, 21, 95, 51, 69, 99]The filter() function returns the list of elements, just like map().Using reduce()reduce() is a functools module function that takes two arguments just like map() and filter(). However, it might also take an initializer as a third argument as the initial value of the accumulator.An example of reduce() with lambda to calculate the sum of a list:from functools import reduce my_list = [5, 8, 12, 25, 50, 500] sum = reduce((lambda x, y: x + y), my_list) print(sum) 600The Pythonic Nature of Lambda ExpressionsThe style guide of Python, PEP 8 discourages lambdas and recommends using normal functions since it is more beneficial. On the other hand, though lambda functions have some good uses in Python, they have a lot of limitations.Lambdas are meant to be used as anonymous functions that will be used especially with functions like map(), filter(), and reduce(). So, you can consider them to be Pythonic since they are quick and elegant in their use and they depend on how you use them.In simple terms, lambdas are considered Pythonic if there are no Pythonic elements available other than that.SummaryLet us sum up what we’ve learned in this article so far:Lambdas and Anonymous Functions.Where should we use a lambda.When should we use a  regular function.Lambda expression abuses.Appropriate uses of Lambdas.Lambda alternatives.Pythonic nature of Lambda.Python lambdas are considered as salt. If used in small amounts, it will enhance the flavor but if used more, the dish will be spoiled. If you are intending to know more about Lambda and Lambda Calculus, you can refer to the following links—Lambda CalculusLambdasTo gain more knowledge about Python tips and tricks, check our Python tutorial and get a good hold over coding in Python by joining the Python certification course.
Rated 4.5/5 based on 12 customer reviews

How To Use Python Lambda Functions

9011
How To Use Python Lambda Functions

Modern-day programming languages like Python and other programming languages like C, C#, and Java have added lambda functions to their syntax to increase the functionality of the languages.

Python Lambdas are anonymous functions which are small and restricted and come without an identifier.

Lambda Calculus is a universal model of computation which was formalized by Alonzo Church in the 1930s. In simple terms, it is a formal system in mathematical logic that is based on pure abstraction and can encode any Turing Machine.

The two models of computations— lambda calculus and Turing machines can be translated into one another. This equivalence is known as the Church-Turing Hypothesis. However, the lambda calculus is Turing complete and does not keep any state, unlike the Turing machine.

The Turing machine has led to the discovery of the imperative style of programming. This type of approach requires managing states and comprises of programming with statements which drive the program in steps, using a comprehensive and detailed instruction format. Languages like C, Fortran, or Python uses this type of programming technique.

On the other hand, the lambda philosophy focuses on data abstraction, transformation, and purity. Their approach is declarative in nature and functional languages like Haskell, Lisp, or Erlang directly inherit them.

However, functional features are also a part of the imperative programming style, especially with the implementation of lambda functions in Python or Java.

Although Python is not a functional language, some functional features like map(), filter(), reduce(), and the lambda operator were added to Python in the year 1994. To learn more about such features, join our Python certification course.

What are Lambdas in Python?

Lambda expressions or lambda forms are used to create anonymous functions. Let us first see an identity function. It is an identity relation or identity map that returns the same argument that was originally provided as input. This is a standard Python definition defined using the def keyword:

>>> def identity(z):
...    return z

On the other hand, a Python lambda function can have any number of parameters and is written in a single line of code. However, the body of the function can have only one expression.

An example of a Python lambda construct:

>>> lambda z: z

The expression above comprises of three essential parts:

  • The lambda keyword.
  • The parameters.
  • The function body.

Another example of a lambda function with an argument:

>>> (lambda z: z + 1)(5)
6

Here, the argument and the function are surrounded by parentheses. The function adds 1 to the argument.

Since lambda function is an expression, you are allowed to name it whatever you want. Let us perform reduction to compute the value of an expression by naming the lambda function:

>>> add = lambda x: x + 1
>>> add(5)
6

We can also declare multi-argument function by listing arguments and separating them with commas ( , )  but without using parentheses:

>>> name = lambda first_name, last_name: f'The full name is {first.title()} {last.title()}'
>>> name('Alex', 'Pandian')
'The full name is Alex Pandian'

Here, the function add takes two arguments and returns a string by interpolating the two parameters first_name and last_name.

What are Anonymous Functions in Python?

A function without a name is known as an anonymous function in Python. It is created with the help of the keyword lambda.

An example of an anonymous function with two arguments:

>>> lambda a, b: a + b

Here, the function has two arguments x and y and is defined using lambda and is not bound to any variable. The function accepts the two arguments and returns their sum.

However, you can invoke the same function using an interactive interpreter-only feature of Python via the underscore(_):

>>> _(4, 5)
9

In the interactive interpreter, the single underscore(_) is bound to the last expression evaluated which means it points to the last lambda function.

The functions which take one or more arguments and returns the result are known as higher-order functions.

A lambda function can be a higher-order function:

>>> higher_order_function = lambda x, f1: x + f1(x)
>>> higher_order_function(3, lambda x: x * x)
12
>>> higher_order_function(3, lambda x: x + 3)
9

The higher-order functions are considered as built-in functions in the Python Standard Library. Some of the examples are filter(), map(), reduce() or key functions like min(), max(), sort() or sorted().

Python Lambdas vs Regular Functions

Python Lambdas vs Regular Functions| Differences between Lambda functions and regular functions in Python

A Lambda function might be considered a function with a syntax within a programming language which makes the language “sweeter” for human use. It is created to make things easier to read and express.

However, there are a number of precise differences between the regular functions and Python lambdas. The following section highlights them all.

A. Difference in Functions

In fundamental terms, there is almost no difference between a regular function with a single return line and a lambda function. However, let us check what difference it would make while we write it in code:

>>> import dis
>>> sub = lambda a, b: a + b
>>> type(sub)
<class 'function'>
>>> dis.dis(sub)
  1           0 LOAD_FAST                0 (x)
              2 LOAD_FAST                1 (y)
              4 BINARY_ADD
              6 RETURN_VALUE
>>> sub
<function <lambda> at 0x000001E47F3EC268>

The dis module subjects a readable version of the Python bytecode generated by the compiler, which in turn displays the low-level instructions used by the Python interpreter.

Let us try the same with a regular function:

>>> import dis
>>> def sub(x,y): return a + b
>>> type(sub)
<class 'function'>
>>> dis.dis(sub)
  1           0 LOAD_FAST                0 (x)
              2 LOAD_FAST                1 (y)
              4 BINARY_ADD
              6 RETURN_VALUE
>>> sub
<function <lambda> at 0x000001E47F3EC268>

You can see the Python bytecode is similar in both cases. However, what differs is the style of naming. With def, the function is named as sub whereas lambda is used in case of Python built-in function.

B. Difference in Traceback

An example of exception raising using lambda:

>>> divide_by_zero = lambda a: a / 0
>>> divide_by_zero(2)
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "<stdin>", line 1, in <lambda>
ZeroDivisionError: division by zero

When you’re using a lambda expression, the traceback of an exception identifies only the function, resulting in the exception as <lambda>.

On the other hand, when you’re using a regular function, the traceback provides the name of the function in particular:

>>> def divide_by_zero(a): return a / 0
>>> divide_by_zero(2)
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "<stdin>", line 1, in divide_by_zero
ZeroDivisionError: division by zero

The traceback returns the function name divide_by_zero.

C. Difference in Syntax

A lambda expression differs in syntax from a normal function in a number of ways:

  1.  Expressions and Statements

A lambda function can contain only expressions and cannot include any statements. It will raise a SyntaxError upon using statements like return, assert or raise.

Let us see an example of using an assert statement in a lambda function:

>>> (lambda a: assert a == )(2)
SyntaxError: invalid syntax

The interpreter raises an error while parsing the code since assert is not a valid keyword in a lambda expression.

  1.  Single Expression

In a Python lambda expression, you can distribute the expression across several lines using parentheses or a multi-line string. But the function will still remain as a single expression:

>>> (lambda a:
... (a % 2 and 'odd' or 'even'))(5)
'odd'

The lambda expression above spreads over two lines but still remains a single expression which evaluates a number and results into odd or even depending upon the argument.

  1.  Annotations

You can use Python type hints and type checking when you’re using normal functions:

def name(first_name: str, last_name: str) -> str:
    return f'{first_name.title()} {last_name.title()}'

If there are any errors with the function name, it can be caught using packages like mypy or pyre. On the other hand, if you’re using a lambda expression, a SyntaxError will be raised:

>>> lambda first_name: str, last_name: str: first_name.title() + " " + last_name.title() -> str
 File "<stdin>", line 1
    lambda first: str, last: str: first.title() + " " + last.title() -> str
SyntaxError: invalid syntax
  1.  IIFE

Immediately Invoked Function Execution or IIFE is a JavaScript function that gets executed as soon as it is defined. However, you cannot use it outside the Python Interpreter.

An example of such is:

>>> (lambda a, b: a + b)(4,6)
10

The IIFE is mainly used to pass the definition of a Python function into a higher-order function like map(), filter() or reduce().

D. Difference in Arguments

Python supports different ways of passing arguments in a lambda expression just like regular functions. Some of which are as follows:

  • Named arguments.
  • Variable list of arguments.
  • Positional arguments.
  • Variable list of keyword arguments.
  • Keyword only arguments.

An example to illustrate different ways of passing arguments in a lambda function:

>>> (lambda a, b, c: a + b + c)(1, 2, 3)
6
>>> (lambda a, b, c=3: a + b + c)(1, 2)
6
>>> (lambda a, b, c=3: a + b +c)(1, b=2)
6
>>> (lambda *arg: sum(arg))(1,2,3)
6
>>> (lambda **kwarg: sum(kwarg.values()))(number_one=1, number_two=2, number_three=3)
6
>>> (lambda a, *, b=0, c=0: a + b + c)(1, b=2, c=3)
6

E. Difference in Decorators

A decorator is a function that accepts another function and allows adding a behavior to a function or class. Its syntax is @decorator which is written before a function.

An example of a decorator is:

def decorator(a):
    def wrap(*arguments):
        print(f"Calling function '{a.__name__}'")
        return a(arguments)
    return wrap
@decorator
def decorated_func(x):
    print(f"With argument '{x}'")

If we invoke decorated_func(“Hello World”), the output will be as follows:

Calling function 'decorated_func'
With argument 'Hello World'

The function decorated_func() prints With argument 'Hello World', but the decorator adds a behavior and also prints  Calling function 'decorated_func'

An example of applying decorator in lambda function is mentioned below:

# Defining a decorator
def trace(a):
  def wrap(*arg, **kwarg):
print(f"[TRACE] func: {f.__name__}, args: {arg}, kwarg: {kwarg}")
return a(*arg, **kwarg)
  return wrap
# Applying decorator to the function
@trace
def add(t):
    return t + 2
# Calling the decorated function
add(3)
# Applying decorator to a lambda function
print((trace(lambda y: y ** 2))(3))

If we execute the following code, we’ll get the following output:

[TRACE] func: add, arg: (3,), kwarg: {}
[TRACE] func: <lambda>, arg: (3,), kwarg: {}
9

The function add is decorated with @trace and invoked. The lambda function gets implemented to the decorator. The lambda function name is <lambda> and the regular function is add.

F. Difference in Closures

A closure is a function object that remembers values and is bound to a specified value in the enclosing scope of that function. In simple words, closure is a record that stores a function and defines the environment in which they run.

Both lambda functions and regular functions can be implemented as closures.

An example to show a closure construct with a regular function:

def outer_function(a):
    b = 4
    def inner_function(c):
        print(f"a = {a}, b = {b}, c = {c}")
        return a + b + c
    return inner_function
 
  for i in range(5):
    closure = outer_function(i)
    print(f"closure({i+5}) = {closure(i+5)}")

inner_function() is a nested function that is being returned by outer_function(). The nested function evaluates the sum of three arguments. The outer_function() is invoked 5 times in a for loop resulting in the output:

x = 0, y = 4, z = 5
closure(5) = 9
x = 1, y = 4, z = 6
closure(6) = 11
x = 2, y = 4, z = 7
closure(7) = 13
x = 3, y = 4, z = 8
closure(5) = 15
x = 4, y = 4, z = 4
closure(5) = 017

An example to show closure using a Python lambda function:

def outer_function(a):
    b = 4
    return lambda c: a + b + c
 
for i in range(5):
    closure = outer_function(i)
    print(f"closure({i+5}) = {closure(i+5)}")

The output of the above code will be:

closure(5) = 9
closure(6) = 11
closure(7) = 13
closure(7) = 15
closure(7) = 17

In both situations, the normal function and the lambda function behaves precisely similar.

G. Difference in Evaluation Time

A lambda function’s behavior as a closure may be counter-intuitive, especially while working with loops.  

Using a regular function:

>>> def wrap(x):
...    def f():
...        print(x)
...    return f
...
>>> numbers = 'one', 'two', 'three'
>>> f1 = []
>>> for x in numbers:
...    f1.append(wrap(x))
...
>>> for f in f1:
...    f()
...
one
two
three

When the function f1 gets appended to the list, is evaluated at definition time.

Let us implement the same using lambda function:

>>> numbers = 'one', 'two', 'three'
>>> f1 = []
>>> for x in numbers:
...    f1.append(lambda: print(x))
...
>>> for f in f1:
...    f()
...
three
three
three

Since n is a free variable bound at runtime  when we invoke the function f, an unexpected error occurs printing three all the time.

However, to get rid of this situation, you can assign the free variable during definition time:

>>> numbers = 'one', 'two', 'three'
>>> f1 = []
>>> for x in numbers:
...    f1.append(lambda x=x: print(x))
... 
>>> for f in f1:
...    f()
...
one
two
three

The lambda argument is initialized with a default value. So, when the function is invoked, the default value x set at definition time is used.

Testing Lambdas

You can test Python lambdas similarly like regular functions with the help of two modules— unittest and doctest.

unittest

Testing Python lambda function using unittest:

import unittest
add = lambda x: x + 2
class Lambda_Testing(unittest.TestCase):
    def test_add1(self):
        self.assertEqual(add(2), 4)
    def test_add2(self):
        self.assertEqual(add(2.2), 4.2)
    def test_add3(self):
        # Should fail
        self.assertEqual(add(3), 6)
if __name__ == '__main__':
    unittest.main(verbosity=2)

The function Lambda_Testing tests three methods, each implemented as a lambda function. After execution, the Python file produces the following output:

$ python lambda_unittest.py
test_add3 (__main__.Lambda_Testing) ... FAIL
test_add1 (__main__.Lambda_Testing) ... ok
test_add2 (__main__.Lambda_Testing) ... ok
======================================================================
FAIL: test_add_three (__main__.Lambda.Testing)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "lambda_unittest.py", line 18, in test_add_three
    self.assertEqual(add3(3), 6)
AssertionError: 5 != 6
----------------------------------------------------------------------
Ran 3 tests in 0.001s
FAILED (failures=1)

There are two successful test cases and one failure for test_add3. However, if we change the expected result from 6 to 5, the Lambda_Testing will be satisfied for all tests.

doctest

The doctest module tests Python lambdas by extracting Python code from docstring:

add = lambda a: a + 2
add.__doc__ = """Add 2 to a number.
    >>> add(2)
    4
    >>> add(2.2)
    4.2
    >>> add(3) # Should fail
    6
    """

if __name__ == '__main__':
    import doctest
    doctest.testmod(verbose=True)

You can execute the code above using doctest.testmod(), the output will be:

$ python lambda_doctest.py
Trying:
    add(2)
Expecting:
    4
ok
Trying:
    add(2.2)
Expecting:
    4.2
ok
Trying:
    add(3) # Should fail
Expecting:
    6
**********************************************************************
File "lambda_doctest.py", line 16, in __main__.add
Failed example:
    add(3) # Should fail
Expected:
    6
Got:
    5
1 items had no tests:
    __main__
**********************************************************************
1 items had failures:
   1 of   3 in __main__.add
3 tests in 2 items.
2 passed and 1 failed.
***Test Failed*** 1 failures.

Here, the failure of the test result is also because of the same test failures explained above in the execution of test cases. Although  it is possible to use docstrings for lambda functions, Python recommends using docstrings for regular functions rather than lambda functions.

Where should you not use Lambda Expressions?

You can simply say that if there is a situation where lambda expressions are not supported, normal functions would be more suitable in such places.

However, there might be situations when you need to avoid lambda expressions in your code:

  • When it doesn’t follow the Python Style Guide ( PEP 8 ).
  • When it is difficult to read and interpret.
  • When it doesn’t support readability.

Exception Raising 

An example of raising an exception in a Python lambda:

>>> def throw_except(excpt): raise excpt
>>> (lambda: throw_except(Exception('Exception is raised')))()
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "<stdin>", line 1, in <lambda>
    File "<stdin>", line 1, in throw
Exception: Something bad happened

Though there are some really clever ways of raising an exception in Python lambda, it is always suggested to use a normal function. This is because a statement is never correct in syntax in the body of a Python lambda function.

Cryptic Style

Lambda functions are brief in nature, because of which it might be difficult to read. 

An example of a bad writing style lambda  expression:

>>> (lambda _: list(map(lambda _: _ // 2, _)))([1,2,3,4,5,6,7,8,9,10])
[0, 1, 1, 2, 2, 3, 3, 4, 4, 5]

Let us modify this lambda code by naming the variables:

>>> (lambda some_list: list(map(lambda a: a // 2,
list)))([1,2,3,4,5,6,7,8,9,10])
[0, 1, 1, 2, 2, 3, 3, 4, 4, 5]

The code is still difficult to read and understand. However, if we execute the same code using a regular function by distributing the logic across several lines, it would greatly impact the readability of the code:

>>> def divide(list):
      divide = lambda a: a // 2
      return map(divide, list)
>>> list(divide([1,2,3,4,5,6,7,8,9,10])))
[0, 1, 1, 2, 2, 3, 3, 4, 4, 5]

Though this method is not the best, it surely enhances the readability of the code in comparison to the lambda expressions.

Python Class

An example of a Python class using lambda:

class Car:
    """Car with methods as lambda functions."""
    def __init__(s, brand, year):
        s.brand = brand
        s.year = year
    brand = property(lambda s: getattr(s, '_brand'),
                    lambda s, value: setattr(s, '_brand', value))
    year = property(lambda s: getattr(s, '_year'),
                    lambda s, value: setattr(s, '_year', value))
    __str__ = lambda s: f'{s.brand} {s.year}'  # 1: error E731
    honk = lambda s: print('Honk!')     # 2: error E731

If you use a style guide tool like flake8 for checking the code above, it will result in following errors for __str__ and honk:

E731 do not assign a lambda expression, use a def

Since multiple strings like '_brand and'_year' are used, the properties that are difficult to read are inclined to errors.

Ultimately, considering a general rule, you should have a preference for regular functions instead of lambda functions in the context of Python programming.

Where should you use lambda expressions?

Lambdas provide a shortened syntax for writing functions, which return a single expression. Since Python supports functional programming, lambdas are one of the most common use cases in such a paradigm of programming. Lambdas allow a fine way to pass functions as arguments to another function by creating a one-time function and passing it as a parameter.

Let us discuss some situations where using lambdas are very appropriate and also suggested by Python.

Functional Constructs 

Built-in functions like map(), filter(), and functools.reduce(), found in the functools module, are often used along with lambda expressions.

Three examples of those functions along with lambda expressions:

>>> list(map(lambda x: x.upper(), ['alex', 'bob', 'charles']))
['ALEX', 'BOB', 'CHARLES']
>>> list(filter(lambda x: 'o' in x, ['alex', 'bob', 'charles']))
['BOB']
>>> from functools import reduce
>>> reduce(lambda acc, x: f'{acc} | {x}', ['alex', 'bob', 'charles'])
'alex | bob | charles'

There are other functional constructs which are alternatives to these constructs and are considered more Pythonic in nature.

Key Functions

Python key functions are higher-order functions that directly determine the algorithm driven by the key function. They accept a named parameter known as key, which in turn takes a lambda function.

Some of the most commonly used key functions are sort(), sorted, min(), max(), nlargest() and nsmallest().

Let us sort a list of IDs using sorted(), in which each ID is a concatenated string of string id and a  number. To sort the list of IDs with the help of the corresponding number associated, we’ll assign lambda to the key argument:

>>> ids = ['ID1', 'ID9', 'ID11', 'ID3', 'ID25', 'ID200']
>>> print(sorted(ids))#Sorting
['ID1', 'ID9', 'ID11', 'ID3', 'ID25', 'ID200']
>>> sorted_ids = sorted(ids, key=lambda x: int(x[2:]))#Integer sorting
>>> print(sorted_ids)
['ID1', 'ID9', 'ID11', 'ID3', 'ID25', 'ID200']

UI Frameworks

Some of the UI frameworks that use lambda expressions for their UI events are Tkinter, wxPython or .NET Windows Forms.

An example of a Tkinter program using lambda:

import tkinter as t
import sys
window = t.Tk()
window.grid_columnconfigure(0, weight=1)
window.title("Lambda Calculus")
window.geometry("500x200")
label = t.Label(window, text="HELLO WORLD")
label.grid(column=0, row=0)
button = t.Button(
    window,
    text="Reverse the string",
    command=lambda: label.configure(text=label.cget("text")[::-1]),
)
button.grid(column=0, row=1)
window.mainloop()

When the Reverse button is clicked, an event gets fired that triggers the lambda, which in turn changes the label from HELLO WORLD  to DLROW OLLEH.

Though lambda can handle firing events, it is always recommended to use a normal function instead as the lambda ends up being self-contained in a shortcode structure.

The Python Interpreter

Python lambdas are considered as bliss when you use it inside the Python Interpreter. In comparison to regular functions, creating a single-line lambda function to look into some code is much easier. The lambdas in interpreter are just like scrap paper that is useless after being used once and are later thrown away.

The timeit module

timeit is a Python module that is used to time small fragments of Python code. In simple words, it measures the evaluation time of small code snippets.

An example of timeit.timeit() being called directly:

>>> from timeit import timeit
>>> timeit("factorial(100)", "from math import factorial", number = 5)
1.799199999652501e-05

A NameError exception would be raised if the full context of the statement is not passed as a string. So the environment should be set up that is required by the main function to be timed.

However a  cleaner and more readable solution to the above code is by using a lambda function:

>>> from math import factorial
>>> timeit(lambda: factorial(100), number=5)
1.799199999652501e-05

Although the lambda version takes less execution time, the string version has a benefit of executing the functions again.

What are the alternatives of lambda expressions?

The higher-order functions like map(), filter(), and functools.reduce() can be used in place of lambdas by changing the form with lists and generators.

Using map() 

map() takes two arguments— a function and an iterable like string, lists or tuples. It executes the function object for each element and returns a modified list of elements.

An example to illustrate map() with lambda by transforming a string of integers into its capitalized form:

>>> list(map(lambda x: x.capitalize(), ['alex', 'bob', 'charles']))
['Alex', 'Bob', 'Charles']

list() should be invoked so that the iterator gets converted into the modified list which can be shown as output in the Python Interpreter.

Using filter()

filter() accepts two arguments— a boolean-valued function and an iterable. It is an excellent way to filter out all elements of a sequence for only those which returns True.

An example of filter() with lambda which returns all odd numbers from a list:

my_list = [5, 10, 21, 95, 51, 69, 72, 22, 70, 99]
final_list = list(filter(lambda x: (x%2 != 0) , my_list))
print(final_list)
[5, 21, 95, 51, 69, 99]

The filter() function returns the list of elements, just like map().

Using reduce()

reduce() is a functools module function that takes two arguments just like map() and filter(). However, it might also take an initializer as a third argument as the initial value of the accumulator.

An example of reduce() with lambda to calculate the sum of a list:

from functools import reduce
my_list = [5, 8, 12, 25, 50, 500]
sum = reduce((lambda x, y: x + y), my_list)
print(sum)
600

The Pythonic Nature of Lambda Expressions

The style guide of Python, PEP 8 discourages lambdas and recommends using normal functions since it is more beneficial. On the other hand, though lambda functions have some good uses in Python, they have a lot of limitations.

Lambdas are meant to be used as anonymous functions that will be used especially with functions like map(), filter(), and reduce(). So, you can consider them to be Pythonic since they are quick and elegant in their use and they depend on how you use them.

In simple terms, lambdas are considered Pythonic if there are no Pythonic elements available other than that.

Summary

Let us sum up what we’ve learned in this article so far:

  • Lambdas and Anonymous Functions.
  • Where should we use a lambda.
  • When should we use a  regular function.
  • Lambda expression abuses.
  • Appropriate uses of Lambdas.
  • Lambda alternatives.
  • Pythonic nature of Lambda.

Python lambdas are considered as salt. If used in small amounts, it will enhance the flavor but if used more, the dish will be spoiled. If you are intending to know more about Lambda and Lambda Calculus, you can refer to the following links—

To gain more knowledge about Python tips and tricks, check our Python tutorial and get a good hold over coding in Python by joining the Python certification course.

Priyankur

Priyankur Sarkar

Data Science Enthusiast

Priyankur Sarkar loves to play with data and get insightful results out of it, then turn those data insights and results in business growth. He is an electronics engineer with a versatile experience as an individual contributor and leading teams, and has actively worked towards building Machine Learning capabilities for organizations.

Join the Discussion

Your email address will not be published. Required fields are marked *

Suggested Blogs

How to use Split in Python

There are times where we need to break down a large string into smaller strings. In such cases, the split function comes into action. Basically, it is a string manipulation tool in Python.A string is a collection or array of characters in a sequence that is written inside single quotes, double quotes, or triple quotes. A character ‘a’ in Python is also considered a string value with length 1.  Strings represent Unicode character values and are mutable in nature which means the value of a string cannot be altered after it has been declared.  An example of declaring and displaying a string in Python: name = “Python”  print(name[0]) Although we cannot change a string after the declaration, we can split a string into different strings using a variety of different ways in Python.  In this article, we will take a deeper dive and understand how to use Split is in Python. We will begin by understanding what the Split function does, what the need is for such a function and how we work with this function. We will then take a look at Split parameters in Python and the different ways of using the Split function. What is Split in Python? If you have worked on the concatenation of strings that are used to merge or combine different strings into one, the split function performs just the opposite of it. The function scans through a string and separates it when it encounters a separator which has been specified before.  However, if the function does not find any defined separator, it uses white space by default.  The syntax of the Split function is as follows: string.split(separator,max) The separator is a character that has been pre-defined and it gets placed between each variable in the output. The split function depends on the value of the separator variable. What is the need for Split function? The Split function returns a list of words after separating the string or line with the help of a delimiter string such as the comma ( , ) character. Some of the merits of using Split function in Python are listed as follows: It is useful in situations where you need to break down a large string into smaller strings. If the separator is not present within the split function, the white spaces are considered as separators. The split function helps to analyze and deduce conclusions easily. It is also useful in decoding strings encrypted in some manner.  How to work with Split function? Strings variables in Python contain numeric and alphanumeric data which are used to store data directories or display different messages. They are very useful tools for programmers working in Python.  The .split() method is a beneficial tool for manipulating strings. It returns a list of strings after the main string is separated by a delimiter. The method returns one or more new strings and the substrings also get returned in the list datatype.  A simple example of the split function is as follows: x = ‘red,orange,yellow’  x.split(“,”)  [‘red’, ‘orange’, ‘yellow’] Here, we have declared a string variable x with three strings. When the split function is implemented with a comma ( , ) as a separator, the strings get separated with commas in between them.  What are Split parameters in Python? The Split function analyses through a string and separates it whenever the program comes across a pre-defined separator. It depends on mainly three different parameters to optimize the execution of the program: Separator - It instructs Python where to break the string. It works as a delimiter and the string is separated depending upon the pre-defined separator. It is optional which means if the separator is not specified in split, the function uses white space as the default separator. However, if the separator is specified as a string value, the output will be an empty string. Maxsplit-  It specifies the number of times the string can be broken up. It is also optional and it’s default value is -1 which denotes that there are no limits on the number of times a string can be split. If the maxsplit is not defined in the split function, the entire string is scanned and Python separates it whenever a delimiter is encountered.    Return - It returns a list of strings after the split function breaks the string by the specified separator. What are the different ways of using the Split function? Python consists of several different ways by which we can implement the Split function. The different techniques are explained below: Python consists of several different ways by which we can implement the Split function. The different techniques are explained below: Splitting String by Space The split() method in Python splits the string on whitespace if no argument is specified in the function. An example of splitting a string without an argument is shown below: str = “Python is cool”  print(str.split()) The output of the above code is as follows: [‘Python’, ‘is’, ‘cool’] In the example above, we have declared variable str with a string value. You can see that we have not defined any arguments in the Split function, so the string gets split with whitespaces.  Splitting String on first occurrence When we split a string based on the first occurrence of a character, it results in two substrings – the first substring contains the characters before the separator and the second substring contains the character after the separator.  An example of splitting a string on the first occurrence of a character is shown below: str = “abcabc”  print(str.split(c)) The output of the above code is as follows: [‘ab’, ‘abc’] Here, we have declared str with a string value “abcabc”. The split function is implemented with separator as “c” and maxsplit value is taken as 1. Whenever the program encounters “c” in the string, it separates the string into two substrings  – the first string contains characters before “c” and the second one contains characters after “c”.  Splitting a file into a list When you want to split a file into a list, the result turns out to be another list wherein each of the elements is a line of your file. Consider you have a file that contains two lines “First line\nSecond Line”. The resulting output of the split function will be [ “First Line”, “Second line”]. You can perform a file split using the Python in-built function splitlines(). Consider you have a file named “sample.txt” which contains two lines with two strings in each line respectively – “Hi there”, “You are learning Python”. An example of splitting “sample.txt” into a list is shown below: f = open(“sample.txt”, “r”)  info = f.read()  print(info.splitlines())  f.close() The output of the above code is as follows: [‘Hi there’, ‘You are learning Python’] We have a file “sample.txt” which is opened in read (“r”) mode using the open() function. Then, we have called f.read() which returns the entire file as a string. The splitlines() function is implemented and it splits the file into two different substrings which are the two lines contained in “sample.txt”. Splitting a String by newline character (\n) You can split a string using the newline character (\n) in Python. We will take a string which will be separated by the newline character and then split the string. The newline character will act as the separator in the Split function.  An example of splitting a string by newline character is shown below: str = “Welcome\nto\nPython\nSplit”  print(str.split(‘\n’)) The output of the above code is as follows: [‘Welcome’, ‘to’, ‘Python’, ‘Split’] Here, we have declared a variable str with a string that contains newline characters (\n) in between the original string.The Split function is implemented with “\n”  as the separator. Whenever the function sees a newline character, it separates the string into substrings.  You can also perform split by newline character with the help of the splitlines() function. Splitting a String by tab (\t) Tabs are considered as escape characters “\t” in text (.txt) files. When we split a string by tabs, the Split function separates the string at each tab and the result is a list of substrings. The escape character “\t” is used as the separator in the Split function. An example of splitting a string by tab is shown below: str = “Python\tis\ta\tscripting\tlanguage”  print(str.split(“\t”)) The output of the above code is as follows: ['Python', 'is', 'a', 'scripting', 'language'] Here, the variable str is declared with a string with tabs (“\t”). The Split function is executed with “\t” as the separator. Whenever the function finds an escape character, it splits the string and the output comes out to be a list of substrings. Splitting a String by comma (,) We can also split a string by commas (“,”) where commas act as the delimiter in the Split function. The result is a list of strings that are contained in between the commas in the original string.  An example of splitting a string by commas is shown below: str = “Python,was,released,in,1991”  print(str.split(“,”)) The output of the above code is as follows: ['Python', 'was', 'released', 'in', '1991'] Here, the variable str is declared with a string with commas (“,”)  in between them. The Split function is implemented with “,”  as the separator. Whenever the function sees a comma character, it separates the string and the output is a list of substrings between the commas in str. Splitting a String with multiple delimiters You can split a string using multiple delimiters by putting different characters as separator in the Split function. A delimiter is one or more characters in a sequence that are used to denote the bounds between regions in a text. A comma character (“,”) or a colon (“:”) is an example of a delimiter. A string with multiple delimiters can be split using the re.split() function. An example of splitting a string with multiple delimiters is shown below: import re  str = 'Python\nis; an*easy\nlanguage'  print(re.split('; |, |\*|\n',str)) The output of the above code is as follows: ['Python', 'is', 'an', 'easy', 'language'] In the example above, we import the built-in module re which imports the libraries and functions of Regular Expressions. The variable str is declared with a string with multiple delimiters like newline (\n), semicolon (;), or an asterisk (*). There.split() function is implemented with different delimiters as separator and the output is a list of strings excluding the delimiters.  Splitting a String into a list When you split a string into a list around a delimiter, the output comes out to be a partitioned list of substrings. You can take any delimiter as a separator in the Split function to separate the string into a list. An example of splitting a string into a list is shown below: str = “New York-Texas-Colombia”  print(str.split(“-”)) The output of the above code is as follows: ['New York', 'Texas', 'Colombia'] The variable str is declared with a string with dash characters( - ) in between and the Split function is executed with a dash ( - )  as the separator. The function splits the string whenever it encounters a dash and the result is a list of substrings. Splitting a String by hash (#) You can also split any string with a hash character (#) as the delimiter. The Split function takes a hash (#) as the separator and then splits the string at the point where a hash is found. The result is a list of substrings.  An example of splitting a string using a hash is shown below: str = “Python#isa#multi-purpose#language”  print(str.split(“#”)) The output of the above code is as follows: ['Python', 'is a', 'multi-purpose', 'language'] The variable str is declared with a string with hash characters( # ) in between them. The Split function is executed with a hash as the separator. The function splits the string wherever it finds a hash  ( # ) and the result is a list of substrings excluding the hash character. Splitting a String using maxsplit parameter The maxsplit parameter defines the maximum number of splits the function can do. You can perform split by defining a value to the maxsplit parameter. If you put whitespaces as separator and the maxsplit value to be 2, the Split function splits the string into a list with maximum two items.  An example of splitting a string using the maxsplit parameter is shown below: subjects = “Maths Science English History Geography”  print(subjects.split(“ ”,2)) The output of the above code is as follows: ['Maths', 'Science', 'English History Geography']  Here, you can see the variable str is declared with a string of different subject names. The Split function takes whitespace (“ ”) as a separator and the maximum number of splits or maxsplit is 2. The first two strings “Maths” and “Science” are split and the rest of them are in a single string. Splitting a String into an array of characters You can separate a string into an array of characters with the help of the list() function. The result is a list where each of the element is a specific character.  An example of splitting a string into an array of characters  is shown below: str = “PYTHON”  print(list(str)) The output of the above code is as follows: ['P', 'Y', 'T', 'H', 'O', 'N'] Here, the variable str is a string. The string is separated into individual characters using the list() function and the result is a list of elements with each character of the string. Splitting a String using substring You can obtain a string after or before a specific substring with the split() function. A specific string is given as the separator in the Split function and the result comes out to be the strings before and after that particular string.   An example of splitting a string using substring  is shown below: fruits = “Orange Banana Mango Apple Cherry”  print(fruits.split(“Mango”)) The output of the above code is as follows: ['Orange Banana ', ' Apple Cherry'] Here, the variable fruits is a string with names of different fruits. We take the string “Mango” as the separator in the Split function. Whenever the function finds the string “Mango”, it splits the whole string into two substrings – one substring before “Mango” and another substring after “Mango”.  Miscellaneous tips on Split function Since we have now reached at the end of the article, let me give you some useful tips on the Split function: If the maxsplit is not defined in the function and there are enough delimiters in the string, the result will have a length of maxsplit +1.If you want to recombine a string that has been already split in Python, you can perform the concatenation of strings.The Python Split function only works on string variables. If you come across any problem with working with split, you can force the compiler to treat the variable as a string with str(x).Conclusion The .split() function in Python is a very useful tool to split strings into chunks depending upon a delimiter which could be anything starting from characters or numbers or even text. You can also specify the number of splits you want the function to perform using maxsplit, which is used to extract a specific value or text from any given string using list or Arrays. Here are the key areas you should have gained a good understanding on by reading this article: What is a String. What is Split and why is it needed. How does a Python Split function work. What are the Split parameters. What are the many different ways of Splitting strings in Python Important tips on Split You have learned about the Python split function and the different ways to implement in your program. With this, you can begin to work on any project which requires the use of the Split.  If you wish to extend your knowledge about Strings and Split function in Python, you can refer to the official documentation of Python. Also, don’t forget to check out the remaining tutorials made freely available to you. 
Rated 4.0/5 based on 12 customer reviews
6603
How to use Split in Python

There are times where we need to break down a larg... Read More

How to concatenate strings using Python

The string data type in Python is a very important building block of programming. It is basically a sequence of one or more characters that represent Unicode characters. The characters could be letters, numbers, or symbols. The strings are immutable in nature, which means they are unchanging.  You can implement string formatting techniques in Python like merging or splitting strings in Python. When you merge or combine two or more strings in Python, it is called string concatenation. In this article, we will understand what concatenation is and its importance. We will delve into different ways of concatenating strings including the + operator, * operator and % operator and take you through various concatenation methods including the join() method, format() function, the f-string and StringIO methods. What is concatenation in Python? String Concatenation is the operation of joining character strings end-to-end. If you have just started working on Python, you might come through a time when you will need to merge or combine the contents of two or more strings together. In technical terms, this merging or combining of strings together into a single string is called String concatenation. The simplest way to explain concatenation in Python is when you take two separate strings stored in the Interpreter and combine them so that they become one single string. For example, if you take one string as “foot” and another string as “ball” and then merge them into using concatenation technique it comes out to be a single string “football”. There are several ways in which you can perform string concatenation in Python. However, the simplest method is using the “+” operator. What is the need for String formatting in Python? String formatting in Python is a robust and important part of the toolkit of any Python programmer. String formatting techniques have greatly evolved since the time Python was developed. Almost every piece of production software created has its advantage in some way or the other.  Formatted strings in Python are evaluated at run time which acts as a basic capability of any high-level language. At a basic level, String concatenation using the “+” operator might seem inefficient and also difficult to make expressive. This is where Python’s string formatting starting from the “%” formatting to the format() method comes into action. They exhibit great potential when it comes to crafting strings. How can we concatenate strings in Python? Python comprises of a number of ways when it comes to concatenate or combine strings together. Since Python is an object-oriented programming language, everything in Python is an object. So, the new string that is created after concatenation is also referred to as a string object in Python.  Let us see what are the different ways by which we can concatenate strings in Python. Using the + operator The simplest and most common method of concatenating a string is using the plus symbol (“+”). Let us see an example to understand it better: a = “Python”  b = “is”  c = “cool”  print(a + b + c) PythoniscoolHere, we have declared three string variables “a”, “b” and “c” with three different string values. Then, we concatenate the three strings with the help of the “+” operator and display the output using the print statement. The output is the combination of the three strings together.  You might use the “+” operator when you have few strings to concatenate. This is because strings are immutable i.e. they cannot be changed once created. So, for each concatenating statement, the interpreter creates a new object. Thus, it will be quite inefficient if you try to concatenate many strings using the “+” operator. Another disadvantage of the “+” operator is that it does not allow any separator or delimiter between the strings. If you want to concatenate “Hello” and “World” with whitespace as a separator, you need to fo something like this “Hello” + “ ” + “World” and the output will be “Hello World”. Using the * operator The asterisk (*) operator is used when you want to concatenate the same string repeatedly. For example, if you have a string “red” and you want the same string to be concatenated three times, you use the * operator. The result will be “redredred”.  An example to illustrate concatenation of string using “*” operator: a = "Python"  print(a * 3) PythonPythonPython Here, we have declared a single string variable “a” with a string value. Then, we concatenate the string with the help of the “*” operator and display the output using the print statement. The output combines the string with the same string three times repeatedly. Using the join() method The join() method is the most flexible way of concatenating strings in Python. If you have many strings and you want to combine them together, use thejoin() method. It is a string method and the most interesting thing about join() is that you can combine strings using a separator. It works on iterators like lists, tuples, string, dictionaries, etc.  An example to illustrate concatenation of string using “*” operator: a = "Welcome"  b = "to"  c = "Python"  print(“-”.join([a,b,c])) Welcome-to-Python Here, we have declared three string variables “a”, “b” and “c” with three different string values. Then, we concatenate the three strings with the help of the join() method with “-” as a separator and display the output using the print statement. The output is the combination of the three strings together with dash (“-”) operator in between the strings. Using the % operator The modulus operator (“%”) can be used for both string formatting and string concatenation. It is useful for cases in which you need to combine strings and also perform basic formatting. An example to illustrate concatenation of string using “%” operator: a = "Apple"  b = "Shake"  print(“% s % s” % (a, b)) Apple Shake Here, we have declared two string variables “a”, and “b”with two different string values. Then, we concatenate the two strings with the help of the (“%”) and display the output using the print statement.  The “% s” denotes the string data type in Python and the modulus (“%”) operator combines the string stored in the two variables “a” and “b”. The string value in the variables is passed to the string data type and the output is displayed as the combination of two strings. Using the format() function The str.format() function is a powerful function in Python which is also used for both String formatting and String Concatenation. This function combines different elements within a string through positional formatting.     An example to illustrate concatenation of string using format() function: a = "Virgin"  b = "Mojito"  print(“{} {}”.format(a, b)) Virgin Mojito Here, we have declared two string variables “a” and “b”with two different string values. Then, we concatenate the two strings with the help of the format() function and display the output using the print statement.  The curly braces (“{}”) used here are used to fix the string position. The first variable is stored in the first curly braces and the second one in the second curly braces. The job of format() function is to concatenate the strings stored in variables “a” and “b” and display the combined string. Using the f-string  Formatted string literals or f-strings, in short, are string literals in Python. They contain an f at the beginning and curly braces that contain the expressions. It calls the str() method when an object argument is used as field replacement. Let us see an example to illustrate the concatenation of string using f-string: a = "Moscow"  b = "Mule"  print(f’{a} {b}‘) Moscow Mule Here, we have declared two string variables “a” and “b”with two different string values. Then, we concatenate the two strings with the help of the f-string and display the output using the print statement.  The f-string expressions are evaluated at runtime and they are being formatted using the __format__ protocol in Python. It is considered to be a cleaner and easier way of concatenating strings in Python when compared to the format() function.Using StringIO String concatenation using StringIO is also a very flexible way for combining different strings in Python. In this method, we have to import the StringIO() function from the IO module.  An example to illustrate the concatenation of string using StringIO: from io import StringIO  a = StringIO()  a.write(“Machine ”)  a.write(“Learning”)  print(a.getvalue()) Machine Learning Here, we have declared two string variables “a” and “b”with two different string values. Then, we concatenate the two strings with the help of the StringIO() imported from the IO module and display the output using the print statement.  Here, the variable “a”acts as a file object in Python. The write() function is used here to write the string to the file and the getvalue() function returns the entire content of the file. Miscellaneous concatenations in Python We have covered all the ways by which we can concatenate different strings in Python. Let us see some few more miscellaneous examples to understand String Concatenation better. Concatenate multiple strings There are various ways by which you can concatenate multiple strings in Python. The most common among them is using the plus (“+”) operator. You can combine both string variables and string literals using the “+” operator. However, there’s another method that allows an easy way of concatenating multiple strings. It is using the in-place (+=) operator. The in-place operator concatenates the sequence with the right operand and the result gets assigned to that sequence. Let us see an example of string concatenation using the (“+=”) operator: a = "Artificial "  b = "Intelligence"  a += b  print(a) Artificial Intelligence Here, two string variables “a” and “b” are declared with two different string values. The string on the right side of the “+=” operator is combined with the string variable on the left side. Then, the output is displayed using the print statement.  You can also add a string to the end of a string variable using the “+=” operator: a = "Basket"  a += "ball"  print(a) Basketball Another way of concatenating multiple strings in Python is just by writing string literals consecutively: a = "Red""Green""Blue"  print(a) RedGreenBlueConcatenate strings and numbers There are numerous ways of concatenating strings in Python. However, not all methods can concatenate strings and numbers. If you use the “+” operator to combine strings and numbers, it will raise errors. This is because strings can hold any recorded characters but numbers like  integers or floats are recorded number value. a = "Rolls Royce "  b = 1948  print(a + b) Traceback (most recent call last):   File "", line 6, in   TypeError: can only concatenate str (not "int") to str The error shows that the interpreter can concatenate a string value with another string value but cannot concatenate a string value with an integer. Although, you can overcome this problem with the help of the str() function in Python. It converts any integer or floating-point number into a string.  Let us see the same example with the str() function: a = "Rolls Royce "  b = str(1948)  print(a + b) Rolls Royce 1948 The str() function converts the integer value 1948 into a string and then it is concatenated with variable “a” and the output is displayed using the print statement. You can also use the format() function when you need to convert a number with decimal places or zero padding. Concatenate a list of strings into one string You can concatenate a list of strings into one string using the join() method. It takes a character as a delimiter string. If you use an empty string as the delimiter, the list of strings will be simply concatenated without any separator.  Let us see an example to concatenate a list of strings using the join() function: a = ["Apple", "Orange", “Banana”, “Mango”]  print(“\n”.join(a)) Apple  Orange  Banana  Mango Here, the variable “a” is a list declaredwith four different string values. We have used newline (“\n”) as the delimiter in the join() method which inserts a newline for each of the strings. The output is the four strings with each string in a newline. You can use any other delimiter like comma (,) or hyphen (-) in the join() method and then perform concatenation. Also, note that thejoin() method can also concatenate other iterators like tuples, sets, dictionaries, etcConcatenate a list of numbers into one string Python does not allow the concatenation of strings with numbers or numbers with numbers. However, you can convert a numeric value into a string using the str() method and then perform concatenation. If you want to combine a list of numbers into one string, the first thing you need to do is convert each integer in a list to a string using the str() function. Then, combine all the converted strings into a single string with the join() method. Let us see an example to understand it better: a = [1, 2, 3, 4, 5]  b = [str(a) for a in a]  print(“;”.join(b)) 1;2;3;4;5 Here, the variable “a” is a list declared with five integer values. We convert each of the integers into a string using the str() function and store it in variable “b”. Then, we combine them together using the join() method with a colon (;) as the delimiter.Here, the variable “a” is a list declared with five integer values. We convert each of the integers into a string using the str() function and store it in variable “b”. Then, we combine them together using the join() method with a colon (;) as the delimiter. Some useful tips on concatenation Now let me give you some useful tips on String concatenation in Python: The string-formatting operator “%” is a potentially fast and suitable operator when you need to concatenate a few pieces of string. Also, you don’t need to call the str() function when combining numbers because this operator does it implicitly. It also enhances the readability of the code. The join() method is the fastest, cleanest, and most elegant and readable method when you need to concatenate many small pieces of string into a larger string. When you have many small pieces of strings that come either from input or computation and are not in a sequence, always use a list to contain the strings. You can use list comprehension or append method in Python to arrange your list in a sequence.  Conclusion Let us summarize what we have learned in this article so far –  Concatenation and its importance. Different ways of concatenating strings. Some miscellaneous concatenation methods. Important tips on concatenating strings. Concatenation is a crucial part of String manipulation in Python. There are numerous ways to perform concatenation. However, some are more useful than others in some cases.  Now that you have quite an experience in concatenating strings, you can look out for other string formatting methods that Python provides or you can check out the PEP article on Advanced String Formatting on Python.org for more information. 
Rated 4.0/5 based on 14 customer reviews
9825
How to concatenate strings using Python

The string data type in Python is a very important... Read More

How to use sys.argv in Python

The sys module is one of the common and frequently used modules in Python. In this article, we will walk you through how to use the sys module. We will learn about what argv[0] and sys.argv[1] are and how they work. We will then go into how to parse Command Line options and arguments, the various ways to use argv and how to pass command line arguments in Python 3.x In simple terms,Command Line arguments are a way of managing the script or program externally by providing the script name and the input parameters from command line options while executing the script. Command line arguments are not specific just to Python. These can be found in other programming languages like C, C# , C++, PHP, Java, Perl, Ruby and Shell scripting. Understanding sys.argv with examples  sys.argv is a list in Python that contains all the command-line arguments passed to the script. It is essential in Python while working with Command Line arguments. Let us take a closer look with a few examples. With the len(sys.argv) function, you can count the number of arguments. import sys print ("Number of arguments:", len(sys.argv), "arguments") print ("Argument List:", str(sys.argv)) $ python test.py arg1 arg2 arg3 Number of arguments: 4 arguments. Argument List: ['test.py', 'arg1', 'arg2', 'arg3']Module name to be used while using sys.argv To use sys.argv, you will first need to the sys module. What is argv[0]? Remember that sys.argv[0] is the name of the script. Here – Script name is sysargv.py import sys print ("This is the name of the script: ", sys.argv[0]) print ("Number of arguments: ", len(sys.argv)) print ("The arguments are: " , str(sys.argv))Output:This is the name of the script:  sysargv.py                                                                               Number of arguments:  1                                                                                                 The arguments are:  ['sysargv.py']What is "sys. argv [1]"? How does it work? When a python script is executed with arguments, it is captured by Python and stored in a list called sys.argv. So, if the below script is executed: python sample.py Hello Python Then inside sample.py, arguments are stored as: sys.argv[0] == ‘sample.py’ sys.argv[1] == ‘Hello’ sys.argv[2] == ‘Python’Here,sys.argv[0] is always the filename/script executed and sys.argv[1] is the first command line argument passed to the script . Parsing Command Line options and arguments  Python provides a module named as getopt which helps to parse command line options and arguments. Itprovides a function – getopt, whichis used for parsing the argument sequence:sys.argv. Below is the syntax: getopt.getopt(argv, shortopts, longopts=[]) argv: argument list to be passed.shortopts: String of short options as list . Options in the arguments should be followed by a colon (:).longopts: String of long options as list. Options in the arguments should be followed by an equal sign (=). import getopt import sys   first ="" last ="" argv = sys.argv[1:] try:     options, args = getopt.getopt(argv, "f:l:",                                ["first =",                                 "last ="]) except:     print("Error Message ")   for name, value in options:     if name in ['-f', '--first']:         first = value     elif name in ['-l', '--last']:         last = value   print(first + " " + last)Output:(venv) C:\Users\Nandank\PycharmProjects\DSA\venv>python getopt_ex.py -f Knowledge -l Hut Knowledge Hut (venv) C:\Users\Nandank\PycharmProjects\DSA\venv>python getopt_ex.py --first Knowledge –last Hut Knowledge HutWhat are command line arguments? Why do we use them? Command line arguments are parameters passed to a program/script at runtime. They provide additional information to the program so that it can execute. It allows us to provide different inputs at the runtime without changing the code. Here is a script named as argparse_ex.py: import argparse parser = argparse.ArgumentParser() parser.add_argument("-n", "--name", required=True) args = parser.parse_args() print(f'Hi {args.name} , Welcome ')Here we need to import argparse package Then we need to instantiate the ArgumentParser object as parser. Then in the next line , we add the only argument, --name . We must specify either shorthand (-n) or longhand versions (--name)  where either flag could be used in the command line as shown above . This is a required argument as mentioned by required=True Output:  (venv) C:\Users\Nandank\PycharmProjects\DSA\venv>python argparse_ex.py --name Nandan  Hi Nandan , Welcome  (venv) C:\Users\Nandank\PycharmProjects\DSA\venv>python argparse_ex.py -n Nandan  Hi Nandan , Welcome The example above must have the --name or –n option, or else it will fail.(venv) C:\Users\Nandank\PycharmProjects\DSA\venv>python argparse_ex.py --name   usage: argparse_ex.py [-h] --name NAME argparse_ex.py: error: the following arguments are required: --namePassing command line arguments in Python 3.x argv represents an array having the command line arguments of thescript . Remember that here, counting starts fromzero [0], not one (1). To use it, we first need to import sys module (import sys). The first argument, sys.argv[0], is always the name of the script and sys.argv[1] is the first argument passed to the script. Here, we need to slice the list to access all the actual command line arguments. import sys if __name__ == '__main__':     for idx, arg in enumerate(sys.argv):        print("Argument #{} is {}".format(idx, arg))     print ("No. of arguments passed is ", len(sys.argv))Output:(venv) C:\Users\Nandank\PycharmProjects\DSA\venv\Scripts>python argv_count.py Knowledge Hut 21 Argument #0 is argv_count.py Argument #1 is Knowledge Argument #2 is Hut Argument #3 is 21 No. of arguments passed is  4Below script - password_gen.py is used to generate a secret password by taking password length as command line argument.import secrets , sys, os , string ''' This script generates a secret password using possible key combinations''' ''' Length of the password is passed as Command line argument as sys.argv[1]''' char = string.ascii_letters+string.punctuation+string.digits length_pwd = int(sys.argv[1])   result = "" for i in range(length_pwd):     next= secrets.SystemRandom().randrange(len(char))     result = result + char[next] print("Secret Password ==" ,result,"\n")Output:(venv) C:\Users\Nandank\PycharmProjects\DSA\venv\Scripts>python password_gen.py 12 Secret Password == E!MV|,M][i*[Key takeaways Let us summarize what we've learnt so far. We have seen how to use the sys module in Python, we have looked at what areargv[0] and sys.argv[1] are and how they work, what Command Line arguments are and why we use them and how to parse Command Line options and arguments. We also dived into multiple ways to use argv and how to pass command line arguments in Python 3.xHope this mini tutorial has been helpful in explaining the usage of sys.argv and how it works in Python. Be sure to check out the rest of the tutorials on KnowledgeHut’s website and don't forget to practice with your code! 
Rated 4.0/5 based on 14 customer reviews
5910
How to use sys.argv in Python

The sys module is one of the common and frequently... Read More

20% Discount