-1

Say for example I have a list set up like this:

values = ['Godel Escher Bach', 'What if?', 'Thing Explainer', 'Alan Turing: The Enigma', ' 1979', ' 2014', ' 2015', ' 2014', ' Douglas Hofstadter', ' Randall Munroe', ' Randall Munroe', ' Andrew Hodges']

and I want to take every 4 elements (or whatever n i define) and put them into a list of their own, so it would then be

values = [['Godel Escher Bach', 'What if?', 'Thing Explainer', 'Alan Turing: The Enigma'], [' 1979', ' 2014', ' 2015', ' 2014'], [' Douglas Hofstadter', ' Randall Munroe', ' Randall Munroe', ' Andrew Hodges']]

My attempt was to create a for loop and iterate through all the elements and covnert them to lists as such:

values = ['Godel Escher Bach', 'What if?', 'Thing Explainer', 'Alan Turing: The Enigma', ' 1979', ' 2014', ' 2015', ' 2014', ' Douglas Hofstadter', ' Randall Munroe', ' Randall Munroe', ' Andrew Hodges']
for x in range(0,len(values),1):
    values[x:x+4] = [values[x:x+4]]

However, when I try running this, I get

[['Godel Escher Bach', 'What if?', 'Thing Explainer', 'Alan Turing: The Enigma'], [' 1979', ' 2014', ' 2015', ' 2014'], [' Douglas Hofstadter', ' Randall Munroe', ' Randall Munroe', ' Andrew Hodges'], [], [], [], [], [], [], [], [], []]

So my code was what I want it to do, but it also leaves behind a couple of empty []'s, which I do not want. How can I fix this?

EDIT::: NVM, I fixed it.

I did

for x in range(0,int(len(values)/4),1):
    values[x:x+4] = [values[x:x+4]]

and it worked

Thanks to those that took their time to answer this question even though in the end I did not need the help, I appreciate your time.

1 Answers1

0

You should divide length by 4 or n

for x in range(0,len(values)/4):
     values[x:x+4] = [values[x:x+4]]
Oleksandr Dashkov
  • 2,249
  • 1
  • 15
  • 29