tqdm is a Python library used to display progress bars in loops, allowing for a better understanding of the program's execution. It can be used in the console or in Jupyter Notebook, and supports various styles of progress bars. The opportunity to learn about this library arose when I wanted to display progress while processing data, without manually writing conditions like count % 10000 == 0 and printing them out. I found out about this library by researching.
Using tqdm is very simple, you just need to call the tqdm function in the loop. For example, the following code shows how to use tqdm to display a simple loop progress bar:
from tqdm import tqdm
for i in tqdm(range(100)):
# do something
In the above code, we import the tqdm library and call the tqdm function in the loop. The parameter of the function is an iterable object, such as range(100), which means the loop will run 100 times. tqdm will automatically update the progress bar with each iteration.
In addition to the basic usage, tqdm also provides many other functions and parameters to better control the appearance and behavior of the progress bar. Here are some commonly used functions and parameters:
- position: Specifies the position of the progress bar in the console.
- leave: Specifies whether the progress bar should remain in the console after completion.
- desc: Specifies the description text of the progress bar.
- unit: Specifies the unit of the progress bar.
- unit_scale: Specifies the scale factor of the progress bar.
- ncols: Specifies the width of the progress bar.
- bar_format: Specifies the format of the progress bar.
For example, the following code shows how to customize the appearance and behavior of the progress bar using tqdm:
from tqdm import tqdm
for i in tqdm(range(100), position=0, leave=True, desc="Processing", unit="items", unit_scale=0.01, ncols=80, bar_format="{l_bar}{bar:20}{r_bar}{bar:-10b}"):
# do something
In the above code, we specify multiple parameters in the tqdm function. position=0 indicates that the progress bar should be positioned on the first line of the console; leave=True indicates that the progress bar should remain in the console after completion; desc="Processing" specifies the description text of the progress bar as "Processing"; unit="items" specifies the unit of the progress bar as "items"; unit_scale=0.01 specifies the scale factor of the progress bar as 0.01; ncols=80 specifies the width of the progress bar as 80 characters; bar_format="{l_bar}{bar:20}{r_bar}{bar:-10b}" specifies the format of the progress bar as left boundary, progress bar, right boundary, and percentage.
In conclusion, tqdm is a very useful Python library that helps us better understand the execution of programs. It provides various styles and parameters for progress bars, allowing for easy customization of the appearance and behavior of the progress bar. If you often need to process large amounts of data or time-consuming operations, tqdm is a tool worth trying.