0

I'm writing a program to insert element into a list at a position before a particular index. Example,

mylist = [1,2,3,4,5]

enter the index = 3
enter the item = 7

Output:

[1,2,3,7,4,5]

Since the input index is 3, python will append the new item at position index-1 which is 2.

I have tried something like but the output seemed a little off:

mylist = [1,2,3,4,5]

indexInput = int(input("Enter the index: "))
itemInput = int(input("Enter the item: "))

for i in mylist:
    new_slot = indexInput -1
    new_length = len(mylist) + 1
    if i == new_slot:
         mylist[i] = item
         mylist.append(mylist[i])
print(mylist)

I know about the insert() function in python but I'm not allowed to use it so i had to code it the long way. Any help is much appreciated.

0

3 Answers 3

2

You could just use list slicing:

mylist = [1,2,3,4,5]

indexInput = int(input("Enter the index: "))
itemInput = int(input("Enter the item: "))

if indexInput<0:
  indexInput = len(mylist)+indexInput+1

mylist = mylist[:indexInput] + [itemInput] + mylist[indexInput:]
print(mylist)
# for index 3 and item 7 => [1, 2, 3, 7, 4, 5]
# for index -2 and item 6 => [1, 2, 3, 4, 6, 5]

Explanation:

list[start:end:step] => list items from index [start] to index [end-1] with a step of 1
if start is not given, 0 is assumed, if end is not given, it goes all the way to the end of the list, if step is not given, it assumes a step of 1
In my code I wrote:
mylist = mylist[:indexInput] + [itemInput] + mylist[indexInput:]
for indexInput=3 and itemInput=7
mylist = mylist[:3] + [7] + mylist[3:]
mylist[:3] => mylist from 0 (start not given), to 3-1, step of 1 (step not given)
list1 + list2 => a list that contains elements from list1 and list2
mylist[:3] + [7] => [...elements of mylist[:3]..., 7]
mylist[3:] => mylist from 3, to len(mylist)-1 (end not given), step of 1 (step not given)

If you want to do it the long way, here's a solution:

mylist = [1,2,3,4,5]

indexInput = int(input("Enter the index: "))
itemInput = int(input("Enter the item: "))
if indexInput<0:
      indexInput = len(mylist)+indexInput+1
leftSide = []
rightSide = []
for i in range(len(mylist)):
  if i<indexInput:
    leftSide.append(mylist[i])
  elif i>indexInput:
    rightSide.append(mylist[i])
  else:
    leftSide.append(itemInput)
    leftSide.append(mylist[i])

mylist = leftSide + rightSide
print(mylist)
# for index 3 and item 7 => [1, 2, 3, 7, 4, 5]
# for index -2 and item 6 => [1, 2, 3, 4, 6, 5]
Sign up to request clarification or add additional context in comments.

6 Comments

thanks a bunch for the explanation. But if my index were to be negative index, the code won't work.
@Maxxx use the abs() function to get the absolute value of the number in this case, check my updated my answer.
sorry if i wasn't clear, but if negative index were to be used, it means the program will start at the end of the list just like list[-2] = item
If you use abs() it won't start at the end, if the user enters -2, abs(-2) = 2. or do you want it to start from the end?
@Maxxx I updated my answer to support negative indexing.
|
0

Here is my code

mylist = [1, 2, 3, 4, 5]

indexInput = int(input("Enter the index: "))
itemInput = int(input("Enter the item: "))

for idx, val in enumerate(mylist):
    if idx == indexInput:
        mylist = mylist[:idx] + [itemInput] + mylist[idx:]

print(mylist)

Hope it can help you, just use enumerate function to get mylist index

1 Comment

@Mr Geek 's answer is better than mine
0
list = [1,2,3,4,5]
inputIndex = 3
inputItem = 7
temp = 0

for i in range(len(list)):#continuously swap your elements until you reach the end
    if(i == len(list) - 1): # if you're at the end, swap and add the temp to the end
        temp = list[i]
        list[i] = inputItem
        list.append(temp)
    elif(i >= inputIndex):
        temp = list[i]
        list[i] = inputItem
        inputItem = temp

print(list)

This is probably what you're looking for, if this is for an assignment where you're not allowed to use insert then I am assuming you probably aren't allowed to use slicing

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.