Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Partition a list on python

The following code partitions a list in spaces of 5.

o_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200]
 
def partition(lst, size):
    for i in range(0, len(lst), size):
        yield lst[i :: size]

# size of each partition
n = 5

p_list = list(partition(o_list, n))

print("Original List: ")
print(o_list)
print("Partitioned List:")
print(p_list)

The following are the results:

Original List: 
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200]
Partitioned List:
[[10, 60, 110, 160], [60, 110, 160], [110, 160], [160]]

However I want the second array to be [20, 70, 120, 170] and the third and so on follow suit.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Just replace the comma in the range function to a // operator:

o_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200]
 
def partition(lst, size):
    for i in range(0, len(lst) // size):
        yield lst[i :: size]

# size of each partition
n = 5

p_list = list(partition(o_list, n))

print("Original List: ")
print(o_list)
print("Partitioned List:")
print(p_list)

This prints:

Original List: 
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200]
Partitioned List:
[[10, 60, 110, 160], [20, 70, 120, 170], [30, 80, 130, 180], [40, 90, 140, 190]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading