0

Python slicing and list

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']

6th Jan 2022, 4:46 PM
Oral Napier
4 Answers
+ 2
you can use this to insert a fruit in your list : fruits=fruits [0:k]+[input("enter fruit")+fruits[k:] # k is the position where you want to add a new fruit
6th Jan 2022, 5:25 PM
YoPycode
0
The objective was trying to add the fruit watermelon but only some of the words in watermelon i.e. index 1 and 2 This was the expectation I think would have occur. ['apple','wa', 'mango','orange'] šŸŽ šŸ„­ šŸŠ
6th Jan 2022, 5:31 PM
Oral Napier
0
Do you want to add some letters of the new fruit and delete other existing fruits in your list (The second and the third in your example)? if it is the case you can try: fruits=fruits[0] + input("enter a fruit")[0:2] + fruits[3:] that will give you the result you want in the example
6th Jan 2022, 5:53 PM
YoPycode
0
Hope it helps: fruits = [like the example] fruits.insert(1, (input('Enter a fruit: ')[0:2])) print(fruits)
7th Jan 2022, 1:39 AM
Rob
Rob - avatar