0

Basically what i'm trying to do is take every 5 elements from an existing list and then add those elements as a string into another list. For example the below list would output ['12345', '54321']... My attempts so far are below i'm new to coding and would appreciate help best regards Jake

string = ['1', '2', '3', '4', '5', '5', '4', '3', '2', '1']
counter = len(string)
holder = ''
final = []

while counter > 0:
    for i in string:
        if len(holder) >= 5:
            final.append(holder)
            holder = ''
            counter -= 1
        else:
            holder += i
            counter -= 1

Current output gives me this ['12345'] with holder containing '4321' and counter equaling 0 i guess the fact that the '5' is missing has caused the if statement not to trigger but where has the missing '5' Gone

Dead_Ling0
  • 171
  • 1
  • 1
  • 13
  • 1
    You should use `str.join` on each iteration of the itertools `grouper` recipe found in the duplicate question – Adam Smith Dec 03 '15 at 23:20
  • 1
    In general this kind of looping with a counter and a `while` loop is poor form in Python. If you need to do something `n` times, you use `for _ in range(n)`. If you're not sure how many times you do it, you use `while True` with a conditional `break` inside the loop – Adam Smith Dec 03 '15 at 23:22
  • 1
    The reason the `5` disappeared is because in that iteration, `len(holder) >= 5` was `True`. In that case, your code says it doesn't have to save `i` anywhere. Maybe instead you should just have the `if` statement append `holder` to `final`, then blank out `holder`, and put the `holder += i` and `counter -= 1` just below that outside of the `if` statement. – Adam Smith Dec 03 '15 at 23:24
  • Thank you Adam really appreciate your help will try and fix it now :) – Dead_Ling0 Dec 03 '15 at 23:26

0 Answers0