Categories
Python Answers

How to split a list into evenly sized chunks with Python?

Sometimes, we want to split a list into evenly sized chunks with Python.

In this article, we’ll look at how to split a list into evenly sized chunks with Python.

How to split a list into evenly sized chunks with Python?

To split a list into evenly sized chunks with Python, we can use list comprehsion.

For instance, we write:

import pprint

lst = list(range(10, 55))
n = 10
chunked = [lst[i:i + n] for i in range(0, len(lst), n)]
pprint.pprint(chunked)

We create the lst list with numbers from 10 to 54.

Then we want to split them to chunks of 10, which we assigned to n.

Then we split the lst list into chunks of size n with:

[lst[i:i + n] for i in range(0, len(lst), n)]

We loop through the lst entries and compute the chunks with lst[i:i + n].

Therefore, chunked is:

[[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
 [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
 [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
 [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
 [50, 51, 52, 53, 54]]

Conclusion

To split a list into evenly sized chunks with Python, we can use list comprehsion.

Categories
Python Answers

How to print colored text to the terminal with Python?

Sometimes, we want to print colored text to the terminal with Python.

In this article, we’ll look at how to print colored text to the terminal with Python.

How to print colored text to the terminal with Python?

To print colored text to the terminal with Python, we can surround the string we’re print with the escape code for the color to print.

For instance, we write:

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKCYAN = '\033[96m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'


print(f"{bcolors.WARNING}Warning{bcolors.ENDC}")

to define the bcolors class with some escape codes for various styles to apply.

\033[0m lets us stop applying the given style from this point onward.

Therefore, the text we print should have a brownish color.

Conclusion

To print colored text to the terminal with Python, we can surround the string we’re print with the escape code for the color to print.

Categories
Python Answers

How to parse a string to a float or int with Python?

Sometimes, we want to parse a string to a float or int with Python.

In this article, we’ll look at how to parse a string to a float or int with Python.

How to parse a string to a float or int with Python?

To parse a string to a float or int with Python, we can use the float or int functions respectively.

For instance, we write:

a = "545.2222"
b = float(a)
c = int(b)
print(b)
print(c)

We call float or int with a to convert a to a float or int respectively.

Then we get:

545.2222
545

We have to use the int function with a float.

But we can use float with a number string.

Conclusion

To parse a string to a float or int with Python, we can use the float or int functions respectively.

Categories
Python Answers

How to make function decorators and chain them together with Python?

Sometimes, we want to make function decorators and chain them together with Python.

In this article, we’ll look at how to make function decorators and chain them together with Python.

How to make function decorators and chain them together with Python?

To make function decorators and chain them together with Python, we can create decorators that calls the function that’s in the decorator’s parameter in the wrapper function.

Then we return the wrapper function.

For instance, we write:

def bread(func):
    def wrapper(*args, **kwargs):
        print('bread')
        func(*args, **kwargs)
    return wrapper

def ingredients(func):
    def wrapper(*args, **kwargs):
        print("ingredients")
        func(*args, **kwargs)
    return wrapper

@ingredients
@bread
def sandwich(food):
    print(food)

sandwich('tomato')    

top create the bread and ingredients decorators.

They take the func parameter.

The wrapper function takes an indefinite number of arguments as indicated by *args and **kwargs.

We call func in wrapper with *args and **kwargs and return wrapper so func function, which is modified by the decorator is called.

Then we modify sandwich with the ingredients and bread decorators.

And finally, we call sandwich with tomato.

As a result, we get:

ingredients
bread
tomato

logged in the console.

The decorators’ print functions are called before the one in sandwich is called.

Conclusion

To make function decorators and chain them together with Python, we can create decorators that calls the function that’s in the decorator’s parameter in the wrapper function.

Then we return the wrapper function.

Categories
Python Answers

How to iterate over rows in a DataFrame in Python’s Pandas library?

Sometimes, we want to iterate over rows in a DataFrame in Python’s Pandas library.

In this article, we’ll look at how to iterate over rows in a DataFrame in Python’s Pandas library.

How to iterate over rows in a DataFrame in Python’s Pandas library?

To iterate over rows in a DataFrame in Python’s Pandas library, we can use a for loop with the iterrows method.

For instance, we write:

import pandas as pd

df = pd.DataFrame({'c1': [10, 11, 12], 'c2': [100, 110, 120]})

for index, row in df.iterrows():
    print(row['c1'], row['c2'])

We create dataframe with the pd.DataFrame class.

We pass in a dictionary with the columns of the dataframe.

Next, we call df.iterrows to return an iterable object with the index and row of the dataframe.

In the loop body, we print the entries of each row.

Therefore, we get:

10 100
11 110
12 120

printed.

Conclusion

To iterate over rows in a DataFrame in Python’s Pandas library, we can use a for loop with the iterrows method.