Top 15 Interesting Tricks Every Python Beginner Must Know

Top 15 tricks every python beginner must know

We have covered Python Data Types and Loops in Python earlier. Hope you find them useful. Moving ahead with our Python learning, in this article we are going to talk about the top 15 interesting tricks every Python beginner must know.

First of all, let us understand about Functions and Methods.

Function –

A Function is an independent block of code that can be called by its name with or without any parameter. We can create a function that does or does not return any value as an output.

Method –

All methods are functions associated with an object of the class in which it is defined.

Now we will explain various Functions and Methods related to Strings and Lists along with some examples.

Python in String related Functions & Methods –

String in python

Title() –

This method can be used to convert the first letter of the words in a string to its upper case. We can get a look at the way we write the title of any article.

a = "corona virus spreads throughout the planet"
a.title()

Swapcase() –

As the name suggests, this method is to convert the uppercase letter to lower case and vice versa.

a = "cORONA vIRUS sPREADS throughout the planet"
a.swapcase()

Split() –

We can use the split method to split a string on a separator. An option to split the string as many times as we want is also available.

a = "My Name Is Donald Trump"
a.split()
a = "My-Name-Is-Donald-Trump"
a.split(sep=”-“)
a = "My-Name-Is-Donald-Trump"
a.split(sep ='-',maxsplit=3)

Replace() –

If we want to replace a word with another, we can use the replace method on the String object.

a = "My Name Is Donald Trump. I like Mickey Donald and McDonald"
a.replace('Donald', 'Obama')

Join() –

To join a string to another iterable string, we use the join method shown below.
a = "."
a.join("UNICEF")

a = “Name “b = “Place”a.join(b)

Index()-

To find the index of the first match of any character in a string, we can use the index method on the String object. The 2 different commands shown below gives the same output that is the first instance of matching of character “C”.

a = "UNICEF"
a.index("C")
a = "UNICEF UNICEF UNICEF"a.index("C")
At times when we want to match a word instead of a letter, the index of the first letter matched in a match situation is given as the output. When a match is not found, a ValueError is thrown.
a = "UNICEF UNICEF UNICEF"
a.index("CEF")

Capitalize() –

To convert the first letter in a string to an upper case, we can use this method.

a = "unicef unicef unicef"
a.capitalize()

Reverse() –

A very interesting method provided in Python is to reverse iterable elements.

a = ["Name", "Surname", "Age", "City"]
a.reverse()
print(a)

Python Lambda Function –

lambda in python

lambda helps code simple anonymous functions. It is a single line function which can have any number of the argument. A Lambda function is restricted to contain only a single expression. These are used when you need a function for a short period. Let us look at some examples.

cube = lambda x : x*x*x
cube(9)

The above code gives the cube of a number. We did not define a function explicitly which simplifies our task to a great extent.

The below set of code allows us to join the two columns of our data Data Frame.

data = {'Name':["Donald" , "Barack" , "Sachin", "Mary"], 'Surname':["Trump","Obama","Tendulkar","Kom"]} 
import pandas as pd
data = pd.DataFrame(data, index=None)
data['Full Name'] = data[['Name', 'Surname']].apply(lambda x: ' '.join(x), axis = 1) 
print(data)

Reversing a string –

reverse_string = lambda s: s[::-1]
reverse_string('hello my name is Anthony Gonsalves')

Python in List related Functions & Methods –

List in python

Counter –

An interesting function we can apply on a list to count the number of occurrences of its elements is named Counter. This makes our task of counting values very easy.

from collections import Counter
list_of_digits = [1,2,3,4,5,5,2,2,2,3,4,5,3,2,1,3,4]
count = Counter(list_of_digits)

Reduce –

If we want to apply a function on a sequence of an iterable list, reduce comes in handy used along with a lambda function. The reduce function works in a below-mentioned manner:

  • The first two elements in the sequence are picked up and the called function is applied on those two to obtain a result
  • The next step is to apply the same function to the result obtained above and the third element from the sequence and the result is saved.
  • This process continues until the sequence of list exhausts.
  • The final result is printed on the console.

To find the maximum number in a list of numeric elements, we use the below provided reduce command.

#Syntax : reduce(function, sequence)
from functools import reduce
list2 = [3,4,5, 33, -33, 234, 1, 223]
reduce(lambda x,y :x if x>y else y , list2)

Filter –

The filter function creates a new iterator from the existing iterable based on some filter condition wherever it gives true value.

#Syntax: filter(function, sequence)
list1 = [1,2,'a',4,5,'b',7,8,9]
list(filter(lambda x : type(x)==int , list1))

Range –

The range is a simple function that helps create a sequence of numbers. We can give three arguments that are start value, stop value and step to generate the sequence.

#Syntax: range(start, stop, step)
for item in range(1,10):
    print(item)

Map –

The map function applies a function on each element of a sequence and returns a map iterable object containing the results.

#Syntax: map(function, iterable)
First_List = [3,6,2,1,9]
list(map(lambda x : x*x, First_List ))

Sort –

As the name suggests, we can apply this method to generate a sorted sequence of an iterable. The ‘reverse’ argument is set to True or False to get a descending or an ascending sorted output.

First_List = [3,6,2,1,9]
(First_List.sort(reverse=True))
print(First_List)

First_List = ['z','x','t','w']
(First_List.sort(reverse=True))
print(First_List)

enumerate –

The enumerate built-in function is very useful when we want to loop over something and have a counter. We can also pass an optional argument ‘start’ which helps us start the index of the counter from wherever we want. By default, the start parameter value is 0. The returned object is an enumerate object.

#Syntax : enumerate(iterable, start)
Names = ["Chris","Kalam","Sandeep"]
Names.sort()
for Roll_no,j in enumerate(Names ,1):
    print('{}:{}'.format(Roll_no,j))

The code above takes a list of names, sorts it, and then uses an enumerate function to generate a counter named as roll_no in this case.

Python Bonus Trick-

A very interesting short cut Python provides is for interchanging values of 2 variables. Usually, it requires another temporary variable to complete the swapping task. Python makes it very easy to swap values with the below set of commands in the image.

swapping two numbers in python

Conclusion –

Being a Python beginner, it is not possible for a learner to know it all from the very start. So here we have provided some very useful simple functions that every beginner must get accustomed to. We are coming up with more on Python for our learners. Stay tuned. Happy Learning!!!

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.