Python Functions Interview Questions: Your Complete Guide
1. What is function in python? What is the need of function?
In Python, a function is a reusable block of code that can be defined once and used several times throughout the course of the program for performing specific tasks. This encourages an organized code structure that is easier to understand.
Why do we need functions?
Avoid Code Replication: If for example, you would need to do the same thing in different places, just write a function and use it.
Organize Code: Functions help break a large program into smaller fighting logical divisions; this makes the code a little more readable and manageable.
Easier to Test and Debug: The division of code into functions allows a tester or debugger to test various codes independently.
Much Improved Reusability: Defined once this code can be reused in future projects and programs as per need.
For example:
def greet (name):
print("Hello,", name)
greet ("Alice")
greet ("Bob")
Here, greet is just a function that can send greetings to any name that has been passed to it.
2. Define function in python. What is the basic syntax?
A function in Python is a named section of a code that performs a particular task. Functions helps in organizing code, reusing it and making it easier to read and maintain.
Basic Syntax of Function in Python:
def function_name(parameters):
# function body
# some code here
return result # (optional)
def: This keyword is used to define a function.
function_name: This is the name you give to your function.
parameters: These are values you pass into the function (optional).
return: This sends back a result from the function (optional).
3. Difference between function defined and function call in python.
In Python, function definition and function call will make sense only when different cases are presented.
1. Function Definition: This is when you create a function using the def keyword. You write the code that is meant to be run by the function when the object/function is called. Now, the function does not do anything, it is just there in a defined state that is ready to be used.
For example:
def greet():
print("Hello!")
Here, greet() is a defined function but it won’t run until you call it.
2. Function Call: This is when you get down to using or invoking a function by simply naming it followed by parentheses(). This tells Python to execute the code defined within the function.
Example:
greet()
This line calls the greet() function and prints:
Hello!
Summary:
Function definition: You tell Python what it is that the function should do.
Function call: You tell Python to actually go ahead and do it.
4. Can you break down the meaning of arguments and parameters in Python functions?
Lets Briefly define:
What are parameters?
Parameters are names that we use when defining a function.
They are like empty boxes, which store values passed to the function.
They tell the function what kind of data it should expect.
For example:
def add(a, b): # i.e. a and b are parameters
return a + b
a and b are therefore called parameters. These parameters have no assigned value yet.
What are arguments?
Arguments are the actual values that you pass when calling a function.
They are the actual data filling the placeholders (parameters).
For example:
result = add(3, 5); # Here 3 and 5 are arguments.
So, here 3 and 5 are the arguments which were passed to fill the placeholder a and b.
To summarize in a few words:
Parameters = variables in the function definition.
Arguments = value you send when calling the function.
They work together to achieve a flexible and reusable function.
5. What do you mean by positional argument in python? How does it function?
Positional arguments are the most widely used types of arguments in Python for passing values to a function. This means that the values should be given in the same order as those defined by the function's parameter list and Python matches each argument to its parameter positionally.
Example:
def greet(name, message):
print(f'Hello {name},{message}')
greet('John', 'welcome to the session!')
Here, "John" goes name and "welcome to the session!" to message. If you change their order the output will also change. Hence, the position of every argument matters.
In short, with positional arguments the order you provide values must match the order the function expects them.
6. How to make use of keyword arguments in python function? What are the pros and cons thereof?
In Python functions, keyword arguments enable passing values into its functions with names of parameters assigned to them, thus making the codes much more readable and easier to interpret.
For Example:
def describe_pet(animal, name):
print(f"I have a {animal} named {name}.")
describe_pet(name="Buddy", animal="dog").
Here, even though we passed the arguments in a different order, Python still knows what value goes to which parameter because we used the parameter names.
Advantages of Keyword Arguments:
Clarity: The value of the argument for the parameters becomes more explicit.
Flexible Order: There is no need to stick to the exact order of parameters.
Safe with optional values: Helps avoid confusion with default or optional arguments.
Disadvantages:
Longer typing: A little longer to write.
Must exactly match parameter names. An error here could spell disaster.
In short keywords make it pretty much easier to read, hence reducing the possibility of making a mistake, especially in a function containing several other parameters.
7. What do default arguments mean in python functions? How does one define them?
Default arguments in Python assign default values to a function's parameters, which can now be omitted by the user unless a change is desired.
How Do You Set Default Arguments?
Setting a default argument is as simple as giving the parameter a default value at the time of writing the function.
Example:
def greet(name, message="How are You!"):
print(f"Hello {name}, {message}")
Now, if you call greet("Priya") it will print "Hello Priya, How are You!" because you didn't give any custom message, so Python took the default one and used it. If you really want to change it, you can call greet("Vikram", "Good Morning!") and it will print "Hello Vikram, Good Morning!"
Why Use It?
Default argument values make your functions easier to use. There is no need to repeat the same values over and over, but this gives you the flexibility to change them if needed. It keeps your code clean and flexible.
8. Can one mix positional and keyword arguments in a function call? What are the rules related?
Yes, you can mix both positional and keyword arguments in a function call in Python, but there is a simple set of rules that one must follow in order to avoid any errors.
Rules:
Positional arguments should come first.
You have to pass all positional arguments before you can pass keyword arguments.
Correct:
def info(name, age, city):
print(name, age, city)
info("Alice", 25, city="New York") # Positional first, then keyword
Wrong:
# Error: positional argument after keyword
info(name="Alice", 25, city="New York")
Each argument should be passed only once
You can't pass the same argument both positionally and with a keyword.
Wrong:
info("Alice", age=25, age=30) # This will raise an error
Why Mix Them?
Mixing can make your code more readable, you might pass required values with position and optional ones using keywords to make it clear what they mean.
So yes, you can mix them, but you should follow the order and don't repeat.
9. What is args in python functions and how does it work?
*args in Python is used in function arguments when the function needs to accept a number of positional arguments. The term "args" may only be a name, one could also use another name, but the asterisk (*) is what creates the work.
How it works:
If you use *args in a function, after the function is called, Python will collect all of the extra position arguments passed to that function in a tuple. This is useful to know for when you don't know exactly how many values someone is going to pass.
Example:
def add_numbers(*args):
total = sum(args)
print("Total:", total)
add_numbers(1, 2, 3) # Total: 6
add_numbers(5, 10, 15, 20) # Total: 50
In this example, args ends up being a tuple:
First call: args = (1, 2, 3)
Second call: args = (5, 10, 15, 20)
This is how *args contributes to improving the flexibility of functions, increasing the number of inputs a system can handle without having to define them all at once.
10. What is kwargs in python functions? How does it work?
**kwargs in Python allows the function to accept any number of keyword arguments those arguments that come as key, value pairs.
Kwargs is an abbreviation for keyword arguments and just like args, it can be anything but the double asterisks** are most important. These key-value pairs are captured and stored into a dictionary inside the function.
How does it work? It will pass to an unnamed argument.
Example:
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=25, city="New York").
Output:
name: Alice
age: 25
city: New York
Here, kwargs is={'name': 'Alice', 'age': 25, 'city': 'New York'}.
Why is it useful? It provides a lot of flexibility to your function. You can provide it with any number of keyword arguments and it will work them right into a dictionary. This is especially good for optional or dynamic data.
11. Explain the return in python functions. Can a function return more values than one?
When utilizing the return statement in a function in Python, the purpose is to give a result back to the point where the function was called. As soon as return is called Python exits the function and returns the value specified in it.
Can a function return multiple values?
Yes, a function can return multiple values. In fact, in Python, it is possible to return multiple values separated by commas, which will get packed into a tuple.
Example:
def get_person():
name = "Alice"
age = 30
city = "New York"
return name, age, city
result = get_person()
print(result)
# Output: ('Alice', 30, 'New York')
# You can also unpack them directly:
name, age, city = get_person()
print(name) # Output: Alice
This shows that in Python, a function can return multiple values, and this feature becomes quite useful when the user needs to send a group of associated data.
12. What if return is not defined explicitly in Python function?
In Python, if you define a function without an explicit return, it automatically returns a None value when called. So if you don't return anything meaningful your function will return a special None value by default.
Example:
def greet(name):
print("Hello, "+name+"!")
result=greet("Alice") print(result) # Output : None
Here, the function greet does not contain a return statement. It only prints a message without returning anything, and thus when you print the result it shows None because that is what the function has returned by default.
Why is it important?
For a function to return a value back to wherever it was called from, you have to use return. If not, Python will think you meant returning None.
13. What is the scope of variables in Python function? Explain local and global scope.
Variable scope refers to the part of the program where the variable can be accessed or used.
1. Local Scope:
A variable that is created inside a function will only be local to that function and as long as the function is running, it can never be used outside of it.
def greet():
message = "Hello"
print(message) # Works
greet()
# print(message)
# This would throw an error: message is not defined
2. Global Scope:
Any variable defined outside any function becomes global. Such variables can be accessed from anywhere within the program, including inside functions (but you cannot modify it inside a function without using the global keyword).
name = "Alice" # Global variable
def say_name():
print(name) # Can access global variable
say_name()
Change Global Variable Inside a Function:
A global variable inside a function must be declared as global:
count = 0
def increase():
global count
count += 1
increase()
print(count) # Output: 1
In summary, local variables occupy space inside functions, while global variables occur in the main body of the code. Knowing the scope helps you avoid unnecessary mistakes and it makes the code easier to handle.
14. How can you access a global variable inside a function in python? What is the global keyword?
You can use a global variable inside a function in Python just as you would if you were using its name without the risk of changing it. However, to change a global variable from within a function, you must use the global keyword.
Access a Global Variable (without changing it):
You do not need anything special to read a global variable inside a function:
x = 10 # Now Global variable:
def show():
print(x) # Accessing global variable
show() # Output: 10
Changing a Global Variable (using global keyword):
However, to update or reassign a global variable inside a function you have to declare that variable as global.
count = 0
def increase():
global count
count += 1 # Now this works because of 'global' keyword
increase()
print(count) # Output: 1
Reason for using global?
The global keyword tells python that you are referring to the outside functiondefined variable and not creating a new local variable. Python treats the name as a new local variable instead of an error as long as you are trying to update it from that function.
Helps in maintaining the scope of your variables, making it clear when you are dealing with data outside the function.
15. What are docstrings in python functions? Why it is so important and how to write them?
Docstrings are special strings in Python used to describe what a function (or class or module) does. They are written just underneath the corresponding function definition and help others (or even yourself, later) to know what the function does, the inputs it accepts and the output it returns.
What is the importance of docstring?
They help in making the code clearer and easier for maintenance.
Tools such as IDEs, document generators, and help() are using them.
They are great especially for teams and big projects where lots of people read or use the code.
How to write a docstring ?
You will write a docstring using three quotes ("") immediately below the function header.
Example:
def greet(name):
"""This function takes a name as parameter and prints a greeting message.
Parameters:
name (str): Name of person to greet.
Returns:
None
"""
print("Hello, {0}!".format(name))
Call the docstring later with:
help(greet)
In summary, docstrings serve like a quick user manual for your functions. They assist you and others to understand what the function is supposed to do without having to read all the code.
16. What are lambda functions in python? When would you like to use one?
In the Python language, lambda functions are anonymous, small and void functions which we define using lambda key word rather than denoting it as def. Lambda are used in case of quick way of writing functions for short tasks usually in places where usage of full function seems unnecessary or too lengthy.
Syntax:
lambda arguments: expression
Example:
square = lambda x: x * x
Print(squarer(4)) # Print: 16
When to use a lambda function:
When one needs a small function for a very short time.
With functions like map(), filter() and sorted() where passing a quick one-line function is helpful.
Example with filter():
numbers = [1, 2, 3, 4, 5]
even = list(filter(lambda x: x % 2 == 0, numbers))
print(even) # Print: [2, 4]
In short: Use lambda functions for short, simple tasks to keep your code cleaner and avoid writing full function definitions for one-liners.
17. Differentiate lambda functions from normal functions within python.
The first thing to mention would be that both the lambda and normal (def) functions define a function, but both differ in many respects.
1. Syntax
Lambda Function: Pretty much direct and follows from the definition of the word lambda.
square = lambda x: x * x
Normal Function: Very much so defined following the definition of the word def.
def square(x):
return x * x
2. Name:
Lambda: Mostly unnamed, hence anonymous.
Normal: Named, except when it is defined over some variable.
3. Return:
Lambda: Automatically return the result value of expression. That is, it does not use a return statement.
Normal: Must be defined to send any value back.
4. Length or Use:
Lambda: To create a short-lived one-liner function.
Normal: Are used for long, reusable, and more complex logic.
5. Functionality:
Lambda: It takes in expressions only, not multiple lines or statements.
Normal: Multi-line, loops, conditions, and much more can come into play.
When to Use:
Use lambda for very quick and short jobs, like in map(), filter(), or sorted().
Use def functions when a function needs to bear a name, does multiple things, or is intended for better readability.
To sum up:
Lambda for all short, fast and pretty simple jobs.
Normal Def for flexibility, power and larger jobs.
18. What higher-order functions are in python? Give an example.
In a Python context, we define higher-order functions as functions that:
take other functions as an argument or return functions as their results.
This behavior is possible because functions under Python can be treated as any other object, passed to other functions, stored in variables or passed as arguments to other functions.
Why should we be concerned with higher-order functions?
They allow writing more flexible and reusable code, thus making it cleaner while passing through repetitive actions like filtering, mapping, applying logic, etc.
Example: How to use map() built in higher order function
def square(n):
return n * n
numbers = [1, 2, 3, 4]
squared_numbers = list(map(square, numbers))
print(squared_numbers) # Output: [1, 4, 9, 16]
In this case, map() takes the function of square and applies that function to every element of the list numbers.
Other common built-in higher-order functions are filter() and reduce() (from functools), as well as user-defined functions that return or accept other functions.
19. Give a brief about closures in python with an example.
A closure in python is a function which remembers the values from its enclosing lexical scope even when it would have been normally inactive and allows one inner function to access variables defined in the outer function even after the running of the outer function has been completed.
Closures are useful as a means of keeping certain data private or maintaining state between function calls without declaring a class.
Example:
def outer_function(text):
def inner_function():
return f"Message: {text}"
return inner_function
my_closure = outer_function("Hello from closure!")
print(my_closure()) # Output: Message: Hello from closure!
inner_function, in this case utilizes the text variable from outer function. So, memory gets preserved by inner_function to remember the value of text even when outer_function completes execution. Thus, it is said to be closure.
20. What's a decorator in python, and why would one use such?
Python decorators are processes that modify other functions' behavior without interfering with the original function's code implementation. You can decorate a function by adding some features: logging, permission checking, execution timing or error handling.
In fact, decorators separate additional tasks from the actual logic of the functions to make a cleaner, more reusable and manageable code.
Example:
def my_decorator(func):
def wrapper():
print("Something before the function runs.")
func()
print("Something after the function runs.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
Output:
Something before the function runs.
Hello!
Something after the function runs.
In the example, @my_decorator added some behavior before and after running say_hello() without touching its code. This is how decorators are used in real projects: authentication, logging, performance tracking, etc.
21. How would one create a decorator in python? What does @ stand for?
You must write a function and pass another function as input to create a decorator in Python that would wrap it within another function (usually called wrapper) and return it. This makes it possible to add additional actions before or after running the original function without altering the original function.
The @ symbol:
The @ symbol is a short syntax in Python. It interprets the decorator and applies it to the function. Instead of writing the line function = decorator(function), one may simply write @decorator above the function definition.
Step by step Example:
# Step 1: Create the decorator
def simple_decorator(func):
def wrapper():
print("Before the function runs")
func()
print("After the function runs")
return wrapper
# Step 2: Use the decorator with @
@simple_decorator
def greet():
print("Hello!")
# This is how you call the decorated function
greet()
Output:
Before the function runs
Hello!
After the function runs
So here the @simple_decorator is telling Python to send the greet function into simple_decorator. The wrapper accompanies the greet() function with additional code before and after it runs. This can be used for logging, timing, validation, etc.
22. Does the decorators take arguments? How to implement?
In fact, it is possible for decorators to take arguments. However, in that case it would require an extra level of wrapping for the decorator to accept any arguments you want to pass along. In other words, the decorator is actually a factory function that returns the decorator. This is also the typical case when providing configuration or options into your decorator.
Creating a decorator with arguments:
The outer function will take the arguments to be passed for the decorator.
The inner function (the decorator) will take as an argument the function that is going to be decorated.
The wrapper will execute the function with those arguments if required.
Here is an example of argument decorator:
def repeat_decorator(times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(times):
func(*args, **kwargs)
return wrapper
return decorator
# Step 2: Applying the created decorator with arguments by the use of @.
@repeat_decorator(times=3)
def say_hello(name):
print(f"Hello, {name}!")
#Step3: Calling that function which is decorated.
say_hello("Alice")
Output:
Hello, Alice!
Hello, Alice!
Hello, Alice!
Explanation:
The repeat_decorator is decorator factory. It takes times as an argument.
It is actually the decorator that will wrap the function say_hello.
It is the wrapper function that will call say_hello the number of times that were passed in.
We now have our specification for wanting to repeat the function 3 times using @repeat_decorator(times=3).
Key Points:
Arguments (times) are taken by the outer function repeat_decorator.
The inner function (decorator) is the actual decorator, which takes the original function as a parameter.
In effect, the wrapper function contains the logic (in this case, executing the function multiple times).
23. What is recursion in python functions? When do you have to consider recursion?
In Python, recursive function refers to a function that has the capability of calling itself to solve a particular problem. It is called a base case because the function performs the operation called recursion every time until it reaches some termination point, which is a base case.
The following are the main elements of recursion:
Base Case: The condition in which the function stops calling itself and returns a final value. Otherwise, there will be indefinite calling which would eventually result in stack overflow error.
Recursive Case: That part of the function which calls itself with altered arguments leading up to the base case.
Important point about Recursion:
Recursion must be considered when
The problem can be subdivided into subproblems: Recursion excels when the task can be broken down into smaller but similar tasks.
When repetitive structures arise: Problems involving structures such as trees, graphs or lists often will require recursion to break them down.
Less Code Work: A solution in recursion can be simpler and more readable than other programming constructs that are more code intensive especially if the program closely resembles the structure of the problem.
Example: Factorial Calculation
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
In this case, it computes 5 * factorial(4) this step repeats until it reaches the base case of factorial(1).
When Not to Use Recursion:
If it has a much better iterative solution (like loops)
If the depth of the recursion is very deep leading to performance issues or hitting the maximum recursion limit in Python.
24. What are some problems in using recursion in python?
Recursion can be very advantageous in Python, but with some issues and limitations you need to be aware of:
1. Stack Overflow: Maximum Recursion Depth Exceeded
There is a limit to how many times a function can call itself in Python. So, if a recursive function does not reach its base case soon enough or if a large-sized problem is being addressed you may be faced with:
RecursionError: maximum recursion depth exceeded
2. Slower
In general, recursive functions are viewed as being somewhat slower since recursion uses more memory and CPU than do loops, particularly in cases when the same subproblem is solved again and again.
3. Harder to comprehend and debug
There are instances when recursive code can be much harder to follow for a beginner than an iterative solution, particularly when deep recursion is in play. After a while, one gets lost in tracing values flowing through the function and function calls themselves.
4. No tail-call optimization.
While many programming languages implement tail-call optimization, Python does not. In simple terms, if a recursive function in Python reaches the end of its implementation, the function calls itself and forth until all function calls are evaluated. Because of this, Python cannot differentiate among all different recursive calls made and ends up using more memory.
Pseudocode for a possible problem:
def count_down(n):
print(n)
count_down(n - 1)
count_down(10000) # Likely to crash with RecursionError
Best Practices:
Use recursion only where it clarifies the logic.
If time performance is an issue, attempt the iterative (loop) solution.
Use memoization (with functools.lru_cache, for example) to avoid repeating work in recursive functions.
25. What is generator function in python? How do they differ from usual function?
A generator function in Python is a function that enables the return of values one at a time using the yield keyword, rather than returning all at once with return. When the function is executing and reaches a yield statement, it will pause execution and will remember its state. When called again, it resumes from where it left off. This comes in handy when memory is an issue, especially with massive datasets.
def count_up_to(n):
i = 1
while i <= n:
yield i
i += 1
for num in count_up_to(3):
print(num)
Output:
1
2
3
The difference between a standard function and a function generator:
A standard function transfers all its data instantly through return.
A generator function returns one value at a time with yield.
Generators are ideal for memory saving, in that they do not cache all values into memory at once.
Generators can be paused and restarted, while regular functions restart every time.
26. What is the yield keyword in python? How does it work in generator functions?
In the Python programming language, the yield keyword returns a value and does not terminate a function inside a generator. On the other hand, a return completely terminates the function but a yield pauses its execution and remembers its state so that the next time its run is called, it can continue from where it last left.
How it Work:
A function with the yield statement never gets executed until called. The calling creates a generator object.
You can then loop (for example, with a for) through each yielded value.
After a yield, the function will wait for the next invocation to continue.
Example:
def count_up_to(n):
i = 1
while i <= n:
yield i
i += 1
Then call like this
for number in count_up_to(3):
print(number)
Output:
1
2
3
So yield provides memory-efficient on-demand data generation—just right for large data sets or streams.
27. What are advantages of generator functions in python?
The following benefits of generator functions in Python could be useful in handling data which is too big or for more control over how values are generated:
1. Memory Efficient
Generations do not store the finished outcome for memory. It generates them one at a time. It perfectly fits large data or infinite sequences, thereby saving memory.
2. Starts Faster
It will start generating a result immediately upon yielding the next value instead of generating a complete resultant list before producing the result.
3. Cleaner Code
The type of code generation is simpler when it comes to looping with data. A simple for loop may be used to obtain the values from which it was being consumed.
4. Pause and Resume
With yield, a generator function can suspend executing, send a value back and then be resumed where it left off next time it's called. This is very useful when it comes to managing complicated data flows.
5. Works Well with Loops
For use within a for loop, next() or any other iteration tool, it would be unnecessary to worry about indexing or using counters.
For Example:
def even_numbers(limit):
num = 0
while num <= limit:
yield num
num += 2
Loop this generator:
for n in even_numbers(10):
print(n)
This gives you: 0, 2, 4, 6, 8, 10 — one at a time, without holding the whole list in memory.
28. Explain function annotations in python. Are they guaranteeing by interpreter?
Function Annotations in Python
The function annotations in Python allow you to give information about the types of the arguments and the return of a function. These annotations will have no impact on how the function works, they will only be references.
Here's an example of that:
def greet(name: str, age: int) -> str:
return f"Hello, {name}. You are {age} years old."
Now in this case:
name: str indicates that name is to be a string.
age: int indicates that an age is supposed to be an integer.
-> str tells us the function would return a string.
Are Annotations Enforced?
No, Python does not enforce function annotations. They are just hints and raise no error in case the actual data types are different. The Python interpreter ignores them during execution.
So, this will still run:
greet(123, "twenty")
Though the arguments do not match the annotations, Python won't complain.
Why Use Them?
To better understand your code.
For tools like type checkers (mypy, Pyright).
Better IDE support (e.g. autocompletion, linting).
In short, annotations help developers, but Python won't make you stick to them.
29. How to pass functions as argument into other functions in python?
In Python, you may pass a function to another function as an argument much like you would pass a variable. This works because functions are treated as first-class objects in Python. This means we may store them in variables, pass them to other functions and return them from functions.
Example:
def square(x):
return x * x
def apply_function(func, value):
return func(value)
result = apply_function(square, 5)
print(result) # Output: 25
Explanation:
The square is a simple function that takes in a number and returns its square.
The apply_function is taking in another function func and a value and is calling func with the value.
We provided square as an argument, and inside apply_function, it was called.
When to Use:
When you want to apply different behaviors to data using the same code structure.
When dealing with built-in like map(), filter() or your custom decorators.
30. What are the commonly built-in functions in python that one mostly use?
The following is the list of some commonly used built-in functions in the Python programming language in day-to-day working:
1. print()
Displays output on the screen.
print("Hello, world!")
2. len()
Returns the length of sequences like lists, strings, or tuples.
len("Python") # 6
3. type()
Used to get data-type of a certain value or variable.
type(42) # Output: <class 'int'>
4. int(), float(), str()
Used to convert one type of value into another.
int("10") # 10
float("3.5") # 3.5
str(100) # '100'
5. input()
Used to get input from the user as a string.
name = input("Enter your name: ")
6. range()
Used to generate a sequence of numbers, often in loops.
for i in range(5):
print(i)
7. sum()
Gives a sum of an iterable, such as a list.
sum([1, 2, 3]) # Result: 6
8. max() and min()
Gives the maximum or minimum from a sequence.
max([5, 10, 3]) # Result: 10
min([5, 10, 3]) # Result: 3
9. sorted()
Returns a new sorted list from the given iterable.
sorted([3, 1, 2]) # Result: [1, 2, 3]
10. list(), tuple(), set(), dict()
Converts values to these types.
list("abc") # Result: ['a', 'b', 'c']
11. enumerate()
Can be used inside loops to generate the index and the value.
for i, val in enumerate(['a', 'b']):
print(i, val)
12. zip()
Combines elements among two or more iterables.
zip([1, 2], ['a', 'b']) # Results to [(1, 'a'), (2, 'b')]
These built-in functions allow us to write excellent and efficient coding without defining everything from scratch.
Previous Topic==> Python Control Structure FAQ || Next Topics==> String Manipulations Python FAQ
Other Topic==>
Input In Python
Top SQL Interview Questions
Employee Salary Management SQL FAQ!.
Top 25 PL/SQL Interview Questions
Topics Wise Top SQL Interview Questions