Trick #1 - Reversing Strings:
Ever heard of "String Slicing" before?
If not, let me explain it real quick.
In Python a string is immutable, slicing creates a new substring from the source string and the original string remains unchanged.
Using the symbol '[::-1]' any string can be reserved after the variable name:
Trick #2 - Swapping Two Variables:
Swapping in Python occurs when two variables refers to mutually exchanging the values of the variables.
And there several way to achieve this in Python.
The first and most common method is using a temporary variable:
Another way to achieve swapping, is without a temporary variable:
And finally, an alternative method for swapping variables is using the elegance of Python with and Optimal Solution:
Trick #3 - More Than Only Conditional Operator:
To achieve this in a single expression, you have to make use of the logical operators, for example if you you have to print the value of a variable that is greater than 100 and lower than 200, then the code should be something like this:
Combining the conditional operator into a single expression, the code looks something like this:
Trick #4 - Find The Occurrence of All Elements in a List:
Let's say you have the following list:
To find the occurrence of each letter you need to use the 'Counter' method:
Trick #5 - Converting Mutable to Immutable:
This is achievable with the 'frozenset()' function.
Frozen set is an immutable version of a Python set object.
While elements of a set can be modified at any time, elements of the frozen set remain the same after creation.
In this example, since the 'frozenset()' was applied to the list 'list', the item assignment is restricted.
So that's it... hope you'll find it useful (!)
Top comments (1)
Good to see you are using carbon