How to Split a List into Equal Size in Python

In this tutorial, we’ll learn how to program "How to Split a List into Equal Sizes in Python." The objective is to safely and efficiently split a list into equal parts. This tutorial will guide you through the process step by step, ensuring that even remaining elements are handled properly if the list size isn’t perfectly divisible. So, let’s get started!

This topic is straightforward to understand. Just follow the instructions I provide, and you’ll complete it with ease. The program I’ll demonstrate will show you the proper way to split a list. So, let’s dive into the coding process!

Getting Started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Creating Main Function

This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.
  1. def split(list_a, chunk_size):
  2.  
  3.   for i in range(0, len(list_a), chunk_size):
  4.     yield list_a[i:i + chunk_size]
  5.  
  6.  
  7. while True:
  8.   print("\n================= Split a List into Equal Size =================\n\n")
  9.   my_list = [1,2,3,4,5,6,7,8,9]
  10.  
  11.   print("Current List: ", my_list)
  12.   print("\n")
  13.  
  14.   split_size = int(input("Enter the split size: "))
  15.  
  16.  
  17.   print("\n", list(split(my_list, split_size)))
  18.  
  19.   opt = input("\nDo you want to try again?(yes/no): ")
  20.  
  21.   if opt.lower() == 'yes':
  22.     ret=False
  23.   elif opt.lower() == 'no':
  24.     ret=True
  25.     print("Exiting program....")
  26.   else:
  27.     print("Please enter yes/no:")
  28.     break
  29.  
  30.   if ret == False:
  31.     continue

The program takes a list, my_list, and splits it into smaller sublists of equal size, specified by the user as split_size. It defines a function split that uses Python's yield to generate sublists by slicing the original list. The program displays the current list, prompts the user for the chunk size, and outputs the resulting sublists. After displaying the output, the user is asked if they want to repeat the process. If the user chooses "yes," the program restarts; otherwise, it exits with a confirmation message.

Output:

There you have it we successfully created How to Split a List into Equal Size in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

More Tutorials for Python Language

Python Tutorials

Add new comment