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.
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.
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'])
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With