DEV Community

loading...
Cover image for Another 5 Cool Python Tricks

Another 5 Cool Python Tricks

Hugo Estrada S.
SW | Cloud Engineer & Data Scientist
Updated on ・2 min read

Alt Text

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:

Alt Text
Output:
Alt Text

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:

Alt Text
Output:
Alt Text

Another way to achieve swapping, is without a temporary variable:

Alt Text
Output:
Alt Text

And finally, an alternative method for swapping variables is using the elegance of Python with and Optimal Solution:

Alt Text
Output:
Alt Text

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:

Alt Text
Output:
Alt Text

Combining the conditional operator into a single expression, the code looks something like this:

Alt Text
Output:
Alt Text

Trick #4 - Find The Occurrence of All Elements in a List:

Let's say you have the following list:

Alt Text
Output:
Alt Text

To find the occurrence of each letter you need to use the 'Counter' method:

Alt Text
Output:
Alt Text

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.

Alt Text
Output:
Alt Text

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 (!)

Discussion (1)

Collapse
muhimen123 profile image
Muhimen

Good to see you are using carbon