0

I am writing a program in Python and am trying to increment numbers in a list based on certain criteria. My code looks like this:

for i in list1:
     if i+.1 in list2:
         i+=.1
     elif i+.2 in list2:
         i+=.2
     else:
         i = i

However this is not adding anything to i, even if the condition is true. How can I do this? I know list comprehensions, but don't see how that could work in this case.

Syd
  • 401
  • 2
  • 5
  • 13
  • The current answer explains what to do, but it might not solve the problem because floating-point math is not accurate. For example, `0.2 + 0.1` is not exactly equal to `0.3`. You may have to add precision checks or rounding to your program. – TigerhawkT3 Jul 30 '15 at 20:24
  • Why don't you think it's adding anything to `i`? `i` is a copy of what's in the array, not a reference to the array element itself. – Barmar Jul 30 '15 at 20:25
  • Why close as a duplicate? This question, as well as its answer, is much more generic and easier to understand than the duplicate, which is filled with json stuff, complex if sentences and method definitions; just because someone has asked a bad similar question doesn't mean every question should be closed. God I'm starting to hate stackoverflow, let's close good questions and leave awful ones, because the awful one was there first. – Markus Meskanen Jul 30 '15 at 22:06

1 Answers1

2

I suggest to use enumerate to get the indexes of the values and to update the list with the brackets like this:

for i, value in enumerate(list1):
     if value + .1 in list2:
         list1[i] += .1
     elif value + .2 in list2:
         list1[i] += .2
     else:
         list1[i] = value # useless btw

Explanations

In your code, you assign the values of list1 to i, but the values are actually copied in i so when you change i it does not change list1.

To update list1 you have to do list1[index] += .... You can get the index using enumerate.

Moreover as @SvenMarnach said in the comments below, be careful with floating comparisons: for example 0.1 + 0.2 != 0.3 !

clemtoy
  • 1,681
  • 2
  • 18
  • 30
  • I dont really see the purpose of using enumerate. – Syd Jul 30 '15 at 20:23
  • 2
    Last line should be `list1[i] = v`. But why is this even necessary? – Barmar Jul 30 '15 at 20:23
  • Which is important because you want to update the value _at that index_ in the list, not a copy of the value outside of the list. – kojiro Jul 30 '15 at 20:23
  • 4
    This fixes one problem with the code. Another problem is using exact comparison for floating-point numbers, which is bound to fail at some point. – Sven Marnach Jul 30 '15 at 20:25
  • Just as a fun alternative: `newlist = [(val+add if val+add in list2 else val) for val in list1 for add in [.1, .2]]` – bufh Jul 30 '15 at 20:57
  • @clemtoy so how do you compare floats? – Syd Jul 31 '15 at 05:22