'How to make the output of this classic pyramids into list in Python
I want the output for this code to be a list how should I do it I'm very new to python so sorry if this look silly
s = "Hello, World!"
for i in range(len(s)+ 1):
a = print(s[:i])
print(a)
The output would be:
H
He
Hel
Hell
Hello
Hello,
Hello,
Hello, W
Hello, Wo
Hello, Wor
Hello, Worl
Hello, World
Hello, World!
How can I output it like:
[ "H",
"He",
"Hel",
"Hell",
"Hello",
"Hello,",
"Hello, ",
"Hello, W",
"Hello, Wo",
"Hello, Wor",
"Hello, Worl",
"Hello, World",
"Hello, World!",
]
Solution 1:[1]
This is exactly what the itertools.accumulate built-in function does:
from itertools import accumulate
result = list(accumulate('Hello, World!'))
If you prefer something maybe easier to understand:
s = 'Hello, World!'
result = []
for i in range(len(s) + 1):
result.append(s[:i])
The previous approach can also be written using a list comprehension:
s = 'Hello, World!'
result = [s[:i] for i in range(len(s) + 1)]
Solution 2:[2]
You can create an empty list (let's call it string_list)at the beginning of your code and append each substring to that list with string_list.append(s) instead of printing the substring.
Solution 3:[3]
s = "Hello, World!"
my_list = []
for i in range(len(s)):
my_list.append(s[:i+1])
my_list
Output:
['H',
'He',
'Hel',
'Hell',
'Hello',
'Hello,',
'Hello, ',
'Hello, W',
'Hello, Wo',
'Hello, Wor',
'Hello, Worl',
'Hello, World',
'Hello, World!']
The pythonic way is a list comprehension:
s = "Hello, World!"
[s[:i+1] for i in range(len(s))]
Solution 4:[4]
Is this what you're looking for :
print("[")
[print('"' + s[:i] + '"') for i in range(len(s)+ 1)]
print("]")
Solution 5:[5]
s = "Hello, World!"
qqq = []
for i in range(len(s)+ 1):
a = print(s[:i])
qqq.append(s[:i])
print(a)
print(qqq)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Riccardo Bucco |
| Solution 2 | Schnitte |
| Solution 3 | Tamás Pápai |
| Solution 4 | Sowjanya R Bhat |
| Solution 5 | inquirer |
