I have a list ['a','b','c','d'] , want to make another list, like this: ['a', 'ab', abc', 'abcd'] ?
Thanks
Tried:
list1=['a','b','c', 'd']
for i in range(1, (len(list1) 1)):
for j in range(1, 1 i):
print(*[list1[j-1]], end = "")
print()
returns:
a
ab
abc
abcd
It does print what i want, but not sure,how to add it to a list to look like ['a', 'ab', abc', 'abcd']
CodePudding user response:
Use itertools.accumulate
, which by default sums up the elements for accumulation. Since addition (__add__
) is defined for str
and results in the concatenation of the strings
assert "a" "b" == "ab"
we can use accumulate
as is:
import itertools
list1 = ["a", "b", "c", "d"]
acc = itertools.accumulate(list1) # returns an iterator
print(list(acc)) # ['a', 'ab', 'abc', 'abcd']
CodePudding user response:
Append to a second list in a loop:
list1=['a','b','c', 'd']
list2 = []
s = ''
for c in list1:
s = c
list2.append(s)
print(list2)
Output:
['a', 'ab', 'abc', 'abcd']
CodePudding user response:
list1=['a','b','c', 'd']
l = []
for i in range(len(list1)):
l.append("".join(list1[:i 1]))
print(l)
Printing stuff is useless if you want to do ANYTHING else with the data you are printing. Only use it when you actually want to display something to console.
CodePudding user response:
You could form a string and slice it in a list comprehension:
s = ''.join(['a', 'b', 'c', 'd'])
out = [s[:i 1] for i, _ in enumerate(s)]
print(out):
['a', 'ab', 'abc', 'abcd']
CodePudding user response:
You can do this in a list comprehension:
vals = ['a', 'b', 'c', 'd']
res = [''.join(vals[:i 1]) for i, _ in enumerate(vals)]
CodePudding user response:
Code:
[''.join(list1[:i 1]) for i,l in enumerate(list1)]
Output:
['a', 'ab', 'abc', 'abcd']