I have a nested list which contains an integer as the last element of each list, and I am trying to see if the next item in the list is one more than the current item, i.e. if the last element of the current list is 104, if the last element of the next list is 105, do something.
data=[[a,b,c,1200],[a,g,x,3401],[f,a,c,3402],[f,a,c,3403]etc]
for item in data:
if next(item[-1])==item[-1]+1: #if next item is this item plus one
#do something
This keeps raising TypeError: Can't convert 'int' object to str implicitly and I don’t know why. Is there a way to use addition to compare list elements in python that I’m not aware of?
(The next(item) part might not be accurate, as I’m using a function to get previous and next items in the full code, not next(), but it is the same in principle)
This will do what you want.
next(item[-1])does not do what you think. You can deduce this yourself by applying some reasoning:next(), doesn’t receive the actual precursor to the “next” element that you want, that would beitemitem,next()would have to figure out what listitemis part of.itemis in multiple lists? What if it occurs multiple times in the same list? Which item to return?As you can see, there is no possible way to get the next item in a list by simply passing it some random object that happens to be part of some list.
What
next()actually does is quite different. It gives you the next item produced from an iterator/generator.