I am trying to find the index of a new name in the list. I've found the new renters name, but for some reason the index function is not working.
new = ["Maria", "Eric", "Bram", 'Bernardo', 'Bob']
old = ['Karel', 'Maria', 'Eric', 'Bram', 'Bernardo']
newrenter = list(set(new) - set(old))
print(newrenter)
newindex = new.index(newrenter)
print(newindex)
Which outputs:
['Bob']
Then the following error:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [9], in <cell line: 8>()
4 newrenter = list(set(new) - set(old))
6 print(newrenter)
----> 8 newindex = new.index(newrenter)
10 print(newindex)
ValueError: ['Bob'] is not in list
It is probably an easy conversion of the type but I cant find how?
CodePudding user response:
newrenter
is ['Bob']
and as you can see 'bob'
is in your list not ['bob']
.
your code expects a list in another list. but 'new'
only contains string elements.
I can not see your expectation of using .index()
. but I imagine this will helps you:
newindex = new.index(newrenter[0])
And if you need all of remaining items indexes, try this:
new = ["Maria", 'Martin', "Eric", "Bram", 'Bernardo', 'Bob'] # I add Martin for better clue
old = ['Karel', 'Maria', 'Eric', 'Bram', 'Bernardo']
newrenter = list(set(new) - set(old))
for v in newrenter:
print("value:", v, end=" - ")
print("index in new:", new.index(v))
This code will return:
value: Bob - index in new: 5
value: Martin - index in new: 1
CodePudding user response:
new = ["Maria", "Eric", "Bram", 'Bernardo', 'Bob']
old = ['Karel', 'Maria', 'Eric', 'Bram', 'Bernardo']
l = list(set(new) - set(old))
for x in l:
print(new.index(x))