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.
Answers:
Solution without nested loop:
l = ['a','b','c']
res = []
temp = []
for item in l:
temp.append(item)
res.append(temp.copy())
print(res)
This should be the easiest solution:
t=['a','b','c']
x=[]
for i in range(len(t)):
x.append(t[i])
print(x)
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']
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.
Solution without nested loop:
l = ['a','b','c']
res = []
temp = []
for item in l:
temp.append(item)
res.append(temp.copy())
print(res)
This should be the easiest solution:
t=['a','b','c']
x=[]
for i in range(len(t)):
x.append(t[i])
print(x)
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']