Home > Blockchain >  Why I'm getting this kind of output?
Why I'm getting this kind of output?

Time:01-07

I run this code on my desktop and and I enter watermelon and code run ok but it split watermelon letter by letter

fruits = ['apple','pine','grape','mango','orange']
fruits[1:3] = input('Enter a fruit:')
print(fruits)

Output:

Enter a fruit: watermelon 
['apple','w','a','t','e','r','m','e','l','o','n','mango',orange']

Expected output:

['apple','watermelon','mango','orange']

CodePudding user response:

As the comments state, when executing fruits[1:3], you're creating a slice assignment which slices the word which was input and stores it in the 1 and 2 indexes (3 is excluded).

If you were just trying to add another fruit to the array of fruits,

fruits = ['apple','pine','grape','mango','orange']
fruit = input('Enter a fruit: ')
fruits.append(fruit)
print(fruits)

Alternatively, if you really wanted to replace the 2nd and 3rd places, you can do this,

fruits = ['apple','pine','grape','mango','orange']
fruits[1:3] = [input('Enter a fruit: ')]
print(fruits)

Which will produce, ['apple', 'watermelon', 'mango', 'orange']

CodePudding user response:

Since you're doing slice assignment, the source will be treated as a sequence. The slice [1:3] will be replaced by each element of the source sequence separately.

When a string is used as a sequence, each character is a separate element, so it gets split up and inserted into the list.

If you want to replace the slice with the whole string, wrap it in a list.

fruits[1:3] = [input('Enter a fruit:')]

CodePudding user response:

Following on what Barmar commented, try this code.

fruits = ['apple','pine','grape','mango','orange']
fruits[1:3] = [input('Enter a fruit:')]
print(fruits)

It will effectively replace second and third element in array (what I assume you wanted to achieve)

CodePudding user response:

Convert your input to a list explicitly and then assign to your original list.

  •  Tags:  
  • Related