How to append all the input(a string) from user in a list without overwriting the last string
How to append all the input(a string) from user in a list without overwriting the last string
l=["hello","hie","yes","sun be","listen"]
k=input("type to chat: ")
l.append(k)
print(l)
I am trying to append each new element(from user) in the list but every time i run this script only the last element(string) is appended and printed overwriting the previous one.How to add each and every element in the list.Output screen
Every time you run your program, it's a totally blank slate. All memory of previous input is not saved into a database. Do you intend to preserve program state across multiple executions (use a database), or are you attempting to enter multiple entries in one execution (use a loop)?
– ggorlen
Sep 8 '18 at 19:21
At the start of the script you set the list to
["hello","hie","yes","sun be","listen"]
, then you append a single item to it. You will get the same list with a single additional entry every time you run the script. Why would you expect anything else to happen? Even if the list l
did somehow magically persist between execution runs, is is reset each time by that first line.– SiHa
Sep 8 '18 at 20:18
["hello","hie","yes","sun be","listen"]
l
1 Answer
1
with open("text.txt","r") as f:
filo = f.readline()
l = filo.split(",")
k = input("type to chat: ")
fila = open("text.txt", "w")
fila.write(filo+","+k)
fila.close()
print(l+[k])
is this what you wanted?
Exactly this is what I was trying but with a list, is it possible to do the same with a list. How to separate every entry with a comma.
– Kartik
Sep 9 '18 at 5:00
they are now seperated by a comma instead of a space, and it have always used a list. It's caled l = filo.split(",")
– Jonas Wolff
Sep 9 '18 at 6:12
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
i'm not sure what you mean. it out puts ["hello","hie","yes","sun be","listen","the line i just wrote"]
– Jonas Wolff
Sep 8 '18 at 19:19