0

How can save any input to a list?

def savee(): mylist=[] x=input("x: ") mylist.append(x) print(mylist) savee() ................................. when I run this code and insert x then run this code again, mylist is empty, why?? how solve this problem? think we have a window with a qlineedit and a add button, and give input from the qlineedit, when I write a word in qlineedit and click on add button that added to mylist, if I want to add next word to mylist, last word deleting from mylist, whats the problem?

15th Feb 2017, 7:11 AM
hamid
hamid - avatar
8 Réponses
+ 8
You defined the mylist variable in the function scope. Each time you run savee() it resets mylist to blank and appends the input once. You will always end up with a one-element list which will be inaccessible outside savee()
15th Feb 2017, 7:35 AM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 6
You have to define mylist before defining the savee() function. mylist=[] def savee(): x=input("x: ") mylist.append(x) print(mylist) savee() # will add one item to the list savee() # will add another item
15th Feb 2017, 9:32 AM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 3
""" Obviously, you can replace the 'while' loop with a 'for' loop if you want to iterate a known count... Based on the second version of my example code, you can improve it to support both behaviour in one: """ def savee(t="? ", n=0): tmplist = [ ] if n == 0: # loop until empty unser entry while len(tmplist) == 0 or tmplist[-1] != "": tmplist.append(input(t)) del tmplist[-1] else: # loop n times for i in range(n): tmplist.append(input(t)) return tmplist print(savee("x: ",3)) mylist = savee("x: ") print(mylist)
15th Feb 2017, 11:17 AM
visph
visph - avatar
+ 2
you can save string as list this way: list = input().split() divide list elements with a space
15th Feb 2017, 10:02 AM
Yuriy Bondarev
Yuriy Bondarev - avatar
+ 2
""" Even if you use a function, you need a loop to user input several times... inside or outside the function, depending on what is your general use of the function: """ mylist = [] def savee(): x = input("x: ") mylist.append(x) # exit loop when empty user entry while len(mylist) == 0 or mylist[-1] != "": savee() # maybe delete last item del mylist[-1] print(mylist) # ... or: def savee(): tmplist = [ ] # exit loop when empty user entry while len(tmplist) == 0 or tmplist[-1] != "": x = input("x: ") tmplist.append(x) # maybe delete last item del tmplist[-1] return tmplist print(savee()) mylist = savee() print(mylist)
15th Feb 2017, 11:05 AM
visph
visph - avatar
0
thanks, and how can change this code to work correctly?
15th Feb 2017, 7:49 AM
hamid
hamid - avatar
0
thannnnnnks allllllll ;))))
15th Feb 2017, 4:07 PM
hamid
hamid - avatar
- 1
you could pass mylist to the function. def savee(inputlist): x=input("x: ") inputlist.append(x) print(inputlist) return inputlist mylist=[] mylist = savee(mylist)
10th Mar 2017, 3:01 AM
Gabriel Monroe
Gabriel Monroe - avatar