Reputation: 27
This is my code:
#Printing the original list (This was given)
a = ['spam','eggs',100,1234]
a[0:2] = [1,12]
print("This is the original list:", a)
#Prompting user to input data
b = input('Please add your first item to the list: ')
c = input('Please add your second item: ')
a[4:4] = b
a[5:5] = c
#Printing new list
print(a)
When I run it and add items to the list, it prints every character there, so hello becomes 'h','e','l','l','o' Even the numbers do this, could you help me fix this?
Upvotes: 1
Views: 480
Reputation: 10121
note : tested only on python 2.7
the assignment operator expects an iterable in the right-hand side when you do
a[4:4] = b
so when you input
a string, it treats it as an iterable and assigns each value of the iterable to the list.
if you need to use the same code, use [string]
for the input. else use list methods like append
Please add your first item to the list: ['srj']
Please add your second item: [2]
[1, 12, 100, 1234, 'srj', 2]
Upvotes: 0
Reputation: 180411
Because when you add strings to a list like that they become individual character inside the list:
In [5]: l = [1,2,3]
In [6]: s = "foo"
In [7]: l[1:1] = s
In [8]: l
Out[8]: [1, 'f', 'o', 'o', 2, 3]
If you want to add the strings to the end of the list use append
:
In [9]: l = [1,2,3]
In [10]: s = "foo"
In [11]: l.append(s)
In [12]: l
Out[12]: [1, 2, 3, 'foo']
Or wrap the string
in a list
or use list.insert
:
In [16]: l[1:1] = [s] # iterates over list not the string
In [17]: l
Out[17]: [1, 'foo', 2, 3, 'foo']
In [18]: l.insert(2,"foo")
In [18]: l
Out[19]: [1, 'foo', 'foo', 2, 3, 'foo']
Upvotes: 2