-4

Let's say I have a list of words like:

words = ['word1', 'word2', 'word3', 'word4', 'word5', 'word6', 'word7', 'word8']

How do I iterate over it to pull groups of 5 and assign them to a variable as strings which I then run some code and then change the variable so that my output looks something like this:

var = 'word1', 'word2', 'word3', 'word4', 'word5'
print(var)
var = 'word6', 'word7', 'word8'
print(var)
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126

1 Answers1

0

You may use generator expression along with next() to achieve this:

>>> words = ['word1', 'word2', 'word3', 'word4', 'word5', 'word6', 'word7', 'word8']

# generator to returns words in chunk of 5
>>> var = (words[i:i+5] for i in range(0, len(words), 5))

# first print using `next`
>>> print(next(var))
['word1', 'word2', 'word3', 'word4', 'word5']

# second print using `next`
>>> print(next(var))
['word6', 'word7', 'word8']
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
  • 2
    That is a totally valid solution. But. Why would you answer such "question"? It is obvious that OP does not know the basics of Python or is so lazy that he would just copy and paste the solution. There are so many possible solutions even without generators. But OP didn't even try to solve the problem. – Yevhen Kuzmovych Jan 27 '17 at 22:33
  • @YevhenKuzmovych You have a perfectly valid concern. And I agree we should not encourage this behavior. But I do occasionally answer such question which I feel have a potential for too many other users who might be searching for it in the future. For this, I also try to edit the question so that it uses common terms which are generally used by users for searching. PS: I do not know whether I am doing the right thing over here – Moinuddin Quadri Jan 27 '17 at 22:43
  • 2
    That is a good reason. But there are answers to such simple questions on SO already. Even if you try to google this title (`Extract chunks/groups from list with each iteration of variable python`), you will find great, complete (, another) [answer](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks). I believe you have helped a lot of people answering such questions (maybe even me :D ), but I think such simple questions should not be asked (anymore). – Yevhen Kuzmovych Jan 27 '17 at 22:52