Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you split a list every x elements and add those x amount of elements to an new list?

Tags:

I have a list of multiple integers and strings

['-200', ' 0', ' 200', ' 400', ' green', '0', '0', '200', '400', ' yellow', '200', '0', '200', '400', ' red']

I'm having difficulty separating the list every 5 elements and creating a new list with just 5 elements inside.

However, I don't want 3 different lists, i just want one that changes every time a new 5 elements goes through.

like image 689
Tyler Avatar asked Apr 08 '13 23:04

Tyler


People also ask

How do you split a list of elements in Python?

To split a list into n parts in Python, use the numpy. array_split() function. The np. split() function splits the array into multiple sub-arrays.


2 Answers

You want something like:

composite_list = [my_list[x:x+5] for x in range(0, len(my_list),5)]  print (composite_list) 

Output:

[['-200', ' 0', ' 200', ' 400', ' green'], ['0', '0', '200', '400', ' yellow'], ['200', '0', '200', '400', ' red']] 

What do you mean by a "new" 5 elements?

If you want to append to this list you can do:

composite_list.append(['200', '200', '200', '400', 'bluellow']) 
like image 151
Serdalis Avatar answered Oct 12 '22 07:10

Serdalis


I feel that you will have to create 1 new list, but if I understand correctly, you want a nested list with 5 elements in each sublist.

You could try the following:

l = ['-200', ' 0', ' 200', ' 400', ' green', '0', '0', '200', '400', ' yellow', '200', '0', '200', '400', ' red']  new = [] for i in range(0, len(l), 5):     new.append(l[i : i+5]) 

This will step through your first list, 'l', and group 5 elements together into a sublist in new. Output:

[['-200', ' 0', ' 200', ' 400', ' green'], ['0', '0', '200', '400', ' yellow'], ['200', '0', '200', '400', ' red']] 

Hope this helps

like image 44
Nick Burns Avatar answered Oct 12 '22 08:10

Nick Burns