This post includes various features that make Python unique!
Functions can return multiple values
In Python, a function can return more than one value as a tuple. This isn’t possible in a language like Java. There, you can return an array of values instead.
Example 1:
Example 2:
"for" loops and "while" loops can have "else" statements
The "else" statement is not limited to "if" statements. If you add an else block after a "for" or "while" loop, the statements inside the else block are executed only after the loop completes normally. If the loop raises an exception or reaches a break statement, the code under else does not execute. This can be useful for search operations.
"_" gets the value of the last expression
To get the value/result of the last expression, use an underscore. This can be useful when performing mathematical operations.
String literals concatenate together
Two or more string literals (enclosed between quotes) are automatically concatenated.
Function Argument Unpacking
One can unpack a list or a dictionary as function arguments using * and ** respectively. This is commonly known as the Splat operator.
Find the index inside a "for" loop
Wrap an iterable with ‘enumerate’ and it will yield the item along with its index.
Chain Comparison
Conditions may contain more than one comparison at once. You can have a condition that checks whether a value is greater than another and lesser than yet another all at once.
Example 1:
Example 2:
Negative Indexing
Python allows negative indexing for its sequences. Index -1 refers to the last element, -2 refers to the second last element, and so on.
Swapping
Swap the values of two objects.
Repurpose a List
Store all values of List in new separate variables.
Slice Operator
Python’s special Slice Operator. It is a way to get items from lists, as well as change them.
Convert nested list into one list
To a nested list into a single list, import Itertools, a module that implements a number of iterator building blocks to form an ‘iterator algebra’.
Transpose a matrix
The zip() function returns an iterator of tuples based on the iterable objects. This can be used to find the transpose of a matrix.
These were very interesting to read! It is awesome to see some different shortcuts and different functions that allow Python to be more diverse. I was particularly interest in the fact that you can return multiple values in a function.
ReplyDelete