How to add element from last loop iteration to list in python?

Question:

I have this list:

t=['a','b','c']

and want to create the output such as:

['a']
['a','b']
['a','b','c']

I am not sure how to adjust this loop:

for i in t:
  print(i)

I am not sure how to write the loop to create this appending effect from the last iteration and the current iteration. I hope someone can assist.
Thanks.

Asked By: titutubs

||

Answers:

Solution without nested loop:

l = ['a','b','c']
res = []
temp = []
for item in l:
    temp.append(item)
    res.append(temp.copy())
print(res)
Answered By: svfat

This should be the easiest solution:

t=['a','b','c']
x=[]
for i in range(len(t)):
    x.append(t[i])
    print(x)
    
Answered By: Jewel_R

You can use generator/list comprehension, unpacking the list while printing the sliced index and using 'n' as separators:

t = ['a','b','c']

print(*[t[:t.index(i)+1] for i in t], sep='n')

or:

for i in t:
   print(t[:t.index(i)+1])

Output:

['a']
['a', 'b']
['a', 'b', 'c']
Answered By: Arifa Chan
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.