1

I have 2 lists. List A and List B. The values from List B are also in List A, but the values from List A are not all in List B. So List A is longer.

I want to check if a value from List A is in List B and if not, insert it at the index of List A.

So after the loop i want to have 2 identical lists.

I know this alone doesnt make much sense, but I also want to do different things in this loop I havent included here for simplification.

lista = ["apple", "banana", "pinapple", "kiwi", "orange"]
listb = ["apple", "pinapple", "kiwi"]

for i in range(len(lista)):
    if(lista[i] != listb[i]):
        listb.insert(i, lista[i])

print(listb)

When i run this, i get the Error:

Traceback (most recent call last):
  File "test.py", line 5, in <module>
    if(lista[i] != listb[i]):
IndexError: list index out of range

Why am I being an idiot here? I googled for the last 2 hours and am going mad.

4
  • 1
    When i becomes 4, your listb is ['apple', 'banana', 'pinapple', 'kiwi']. So listb[4] doesn't exist. Commented Jul 23, 2021 at 14:25
  • What is your expected results? Commented Jul 23, 2021 at 14:26
  • Don't Google this kind of thing. Debug it. Work out which list access is out of range (is it lista[i] or is it listb[i]?) then print out what that list contents are and what the value of i is at the time it fails, and use this information to work out which of your original assumptions about that list is incorrect. Commented Jul 23, 2021 at 14:26
  • 1
    These problems can often be solved quickly by simply printing all the relevant info during the loop. I did that and could immediately confirm that @not_speshal pointed you in the right direction. It doesn't take hours of googling. Commented Jul 23, 2021 at 14:26

3 Answers 3

2

lista has indices from 0:4, while listb has indices from 0:2. Thus 3 and 4 are invalid indices for listb as initially defined, though this changes during the insertion process.

# Demonstration of indices
lista = ["apple", "banana", "pinapple", "kiwi", "orange"]
listb = ["apple", "pinapple", "kiwi"]

for i in range(len(lista)):
    print(i)
    try:
        print(f'element {i} of list a = {lista[i]}')
    except: 
        print(f'{i} is an invalid index for list a')
    try:
        print(f'element {i} of list b = {listb[i]}')
    except:
        print(f'{i} is an invalid index for list b')

Result:

element 0 of list a = apple
element 0 of list b = apple
element 1 of list a = banana
element 1 of list b = pinapple
element 2 of list a = pinapple
element 2 of list b = kiwi
element 3 of list a = kiwi
3 is an invalid index for list b
element 4 of list a = orange
4 is an invalid index for list b

One potential solution to your task, assuming there is a reason you need to compare and insert values:

for i, v in enumerate(lista):
    if v not in listb:
        listb.insert(i, v)

print(lista)
print(listb)
['apple', 'banana', 'pinapple', 'kiwi', 'orange']
['apple', 'banana', 'pinapple', 'kiwi', 'orange']
Sign up to request clarification or add additional context in comments.

4 Comments

3 becomes a valid index during the process ("banana" is inserted), but 4 isn't.
@Axe319 I did. listb = ['apple', 'banana', 'pinapple', 'kiwi'] before the error. Index 3 becomes valid in the process.
This fails to reproduce duplicates such as ["apple", "banana", "pinapple", "kiwi", "orange","orange"]
Thanks, you were a great help!
0

You have two lists of different sizes. The length of the first one (lista) is 5, meaning that there are 5 elements in it. The length of the second one (listb) is 3. The i variable in your for loop will go through all values returned by the range(len(lista)) function, which is really [0, 1, 2, 3, 4]. As the length of your second list is only 3 that means it will raise errors when asked for an element at index greater than 2.

Comments

0
lista = ["apple", "banana", "pinapple", "kiwi", "orange"]
listb = ["apple", "pinapple", "kiwi"]

for item in lista:
    if item not in listb:
        listb.insert(lista.index(item),item)

print(listb)

Changes:

  • len() function is inappropriately used, as you are not iterating length, but indexes, now the script iterates through every item in lista
  • checks if item is in listb, if not, inserts item at lista's index of that item
  • that's all there is to it!

Hope this helps, but really, try debugging instead of googling next time :)

1 Comment

What happens when there are 2 items with an identical name in the list?

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.