I have a list:
li = ['a','b','c','d']
I want to iterate and combine iteratively the elements in the list such as the first one is combined to the 2nd one and go on. The final output I want is:
['a'],['a','b'],['a','b','c'],['a','b','c','d']
I tried using this way:
for i in range(0, len(li),i):
output = li[:i+i]
print(output)
But I am getting only this result:
[]
['a', 'b', 'c', 'd']
Any idea where I am wrong and how to do this properly?
Your range
values are incorrect, and i
is undefined. This is a much simpler loop:
li = ['a','b','c','d']
for i in range(len(li)):
output = li[:i+1]
print(i, output)
Output:
0 ['a']
1 ['a', 'b']
2 ['a', 'b', 'c']
3 ['a', 'b', 'c', 'd']
You could modify the start
and stop
arguments in your use of range
:
li = ['a', 'b', 'c', 'd']
for i in range(1, len(li) + 1):
output = li[:i]
print(output)
Output:
['a']
['a', 'b']
['a', 'b', 'c']
['a', 'b', 'c', 'd']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.