0

I have a code that checks if the number in the range is even or odd and performs an operation on them respectively. It appends the results of the operation into a list. However, I am trying to append each instance of the for loop as a separate list within a list. How can I modify my code to do this?


series = []
for i in range(13, -0, -1):
    while i > 1:
        if i % 2 == 0:
            i = i//2
            series.append(i)
        else:
            i = i*3+1
            series.append(i)
print(series)

2 Answers 2

1

You need to define the inner list just after the for to get a fresh one at each iterate, then save it in series

series = []
for i in range(13, -0, -1):
    inner = []
    while i > 1:
        if i % 2 == 0:
            i = i // 2
            inner.append(i)
        else:
            i = i * 3 + 1
            inner.append(i)
    series.append(inner)

[[40, 20, ...], [6, 3,...], ...]

You might want to keep the correspondance with the value that led to this list, using a dict like

series = {}
for i in range(13, -0, -1):
    keep_i = i
    inner = []
    while i > 1:
        if i % 2 == 0:
            i = i // 2
            inner.append(i)
        else:
            i = i * 3 + 1
            inner.append(i)
    series[keep_i] = list(inner)

{13: [40, 20,...], 12: [6, 3,...],...}
Sign up to request clarification or add additional context in comments.

2 Comments

The result would be inner list in series list/dictionary. There will be only one item "inner list" in "series list/dictionary" since whatever the condition maybe "i" is appended to "inner list". maybe there should be two lists. Not sure.
@AchuthVarghese From the reading "each instance of the for loop as a separate list" so each run should go in a separate list, that's doesn't talk about the if/else, just each run of the for is in a list
0

You can simply add the [] over each i like so: series.append([i]):

series = []
for i in range(13, -0, -1):
    while i > 1:
        if i % 2 == 0:
            i = i//2
            series.append([i])
        else:
            i = i*3+1
            series.append([i])
print(series)

1 Comment

Thank you, but your example is for while loop, i need it for "for" loop. Azro got it right. Please keep contributing and welcome!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.