Python - Odds and Ends



When we start learning Python, we will begin with the core concepts—variables, data types, loops, conditionals and functions. These are the fundamental building blocks of the programming. Beyond these basics, Python offers a small useful features that makes the code easier and faster.

These extra features don’t always belong to one single category like loops or function. Instead, they are scattered throughout the language. We call them as Odds and Ends because they are like little pieces that complete the bigger picture of the Python.

Odds and Ends

In Python the Odds and Ends are the extra techniques, functions or features that don't fall directly under loops, functions, but helps to write the programs better. They acts as the finishing touches in a program. Let's look at the some of the common odds and ends:

  • Multiple Assignment − assigning values to the multiple variables in a single line.
  • enumerate() function − It helps to get both index and value while looping.
  • zip() function − It combines the two or more lists together.
  • List Comprehensions − It creates a new lists in short, readable way.

Importance of Odds and Ends

Below are the importance of the odds and ends in Python:

  • They helps to write the less code while doing the same task.
  • They make the programs more readable.
  • It allows to solve the problems more efficiently.

Examples of Odds and Ends

Let's explore some of the examples to understand more about the Odds and Ends in Python.

Example 1

Consider the following example, where we are going to assign the values to the variables in a single line, Instead of assigning them one by one.

x, y, z = 11, 12, 13
print(x, y, z)

The output of the above program is -

11 12 13

Example 2

In the following example, we are going to use the enumerate() function to get both index and the value, Instead of managing a counter variable manually.

x = ["Ram", "Ravi", "Rakesh"]
for index, value in enumerate(x):
    print(index, value)

Following is the output of the above program -

0 Ram
1 Ravi
2 Rakesh

Example 3

Following is the example, where we are going to use the zip() function to combine two or more lists in the element-wise.

x = ["Audi", "BMW", "Ciaz"]
y = [11213, 1232133, 1224345]
for name, score in zip(x, y):
    print("Price of ", name, "is", score)

The output of the above program is -

Price of  Audi is 11213
Price of  BMW is 1232133
Price of  Ciaz is 1224345
Advertisements