Reputation: 13
I have a question on how to create a sublist in python.
I want to input 3 values and add them in a sublist with a function and call them 3 times.
But for a reason i cannot create the sublist.
I want my output to be something like this: [['string1','string2','string3'], [10, 20, 30], [2.7, 5.5, 12.2]]
word = input("add text (end stops): ")
list=[]
while word != 'end':
a = int(input("add int: "))
b = float(input("add float: "))
word = input("add text (end stops): ")
def fixlist(lst, st):
list=[]
for item in lst:
list.append(lst)
for y in item:
list.append(st[item])
return [lst, st]
print(fixlist(list, word))
print(fixlist(list, a))
print(fixlist(list, b))
This is my output:
[[], 'end']
[[], 10]
[[], 5.5]
Upvotes: 0
Views: 1092
Reputation: 5833
print("Please provide data!\n-----------------\n")
data = [
[], [], []
]
while True:
line = input("Enter: ")
line = line.split(" ")
if line[0].lower() == "end":
print("\nEntering ended.\n")
break
data[0].append(line[0])
data[1].append(int(line[1]))
data[2].append(float(line[2]))
print(data)
Upvotes: 0
Reputation: 2557
You have a couple of problems in your code:
list=[]
As Patrick mentioned, do not use keywords as variable names.
while word != 'end':
a = int(input("add int: "))
b = float(input("add float: "))
word = input("add text (end stops): ")
When you execute this code, you keep geting new input, but you are throwing away your old input. You need to store your older input if you wish to use it later. for example:
word = input("add text (end stops): ")
all_string_inputs = []
while word != 'end':
all_string_inputs.append(word)
word = input("add text (end stops): ")
In the above code i store the older inputs in the all_string_input
list.
If you wish to enter only 3 values, do not use a while.
def fixlist(lst, st):
list=[]
for item in lst:
list.append(lst)
for y in item:
list.append(st[item])
return [lst, st]
What are you intending to do here? in the above code you iterate over the items in lst
, for which your input is an empty list. And in the end you return your input. Without changing it. Also note that st[item]
is not defined, as item
is not necissarly an int.
If you wish to append to an existing list inside a function, you need to use the following scheme:
def fixlist(lst, st):
lst.append(st)
The above will modify the existing list. If you wish to create a new list, you need to return the new list:
def fixlist(lst, st):
new_list = lst+[st]
return new_list
The above will create a new list with lst
and st
, and returns it.
Try to fix your code now, if that still fails, edit the question with your attempts.
Upvotes: 1