+ 8
Is there any way to dynamically allocate memory to a list on python?
I have tried, S[] = [0] * size and S[] = [None] * size but this still requires me to know the size. Can anyone please help me, if there is a way to go about it?
7 ответов
+ 9
size = int(input("Enter the size of the list: "))
S = [None] * size
+ 7
Thank you both! :)
+ 5
Ah so you can define a function that will allow the user to keep appending at run time, yes?
+ 4
This may help:
S=[] #empty list, with size (len) 0
S.append("your first element")
# the element can be 0 or None
""
You can write as many times "S.append(...)" as you want. The list size will +1 (+=1).
"""
e. g.
S=[]
for i in range(5):
S.append(None)
#will be a list with 5 None, that are not mutually mutable (assume that you know what I mean)
+ 4
#Yes, you can do that.
S=[]
def put_an_item(item) :
S.append(item)
inp=input("Type the first element")
put_an_item(inp)
inp2=input("Type the second element")
put_an_item(inp2)
...
...
(maybe more codes and items)
...
...
print(S)
+ 1
btw python itself a dynamic language ...so when ever you are creating ,adding element the memory will be allocated dynamically.
- 1
no