Yacasu
Yacasu

Reputation: 33

Accumulate strings in a list of strings on each iteration

How can I add elements from a list to another by actualizing the result through iterations in Python ? I've been struggling for hours.

I mean :

li = []
li2 = ['A', 'B', 'C', 'D']

for i in li2:
    li.append(i)

print(li)

#RESULT i am looking for : ['A', 'AB', 'ABC', 'ABCD']

Thanks!

Upvotes: 1

Views: 1023

Answers (3)

yatu
yatu

Reputation: 88236

This can be done quite simply with itertools.accumulate:

from itertools import accumulate
list(accumulate(li2))
# ['A', 'AB', 'ABC', 'ABCD']

Which by default has func=operator.add as function argument:

def accumulate(iterable, func=operator.add, *, initial=None):

So it will add the previous values to the current on each successive iteration.

Upvotes: 2

Mehul Gupta
Mehul Gupta

Reputation: 1939

li = []
li2 = ['A', 'B', 'C', 'D']

for index,i in enumerate(li2):
      li.append(''.join(li2[:index])+i)

Explanation: using enumerate(), you can loop over a list with its index. Now, ''.join() helps us to add any list element as a string.

Upvotes: 0

Code Pope
Code Pope

Reputation: 5449

Do it the following way:

li = []
li2 = ['A', 'B', 'C', 'D']

string = ''
for i in li2:
  string +=i
  li.append(string)

print(li)

Output:

['A', 'AB', 'ABC', 'ABCD']

Upvotes: 1

Related Questions