Python address index +1 with list comprehension Task from CodingBat:


  Return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 is very unlucky, so it does not count and numbers that come immediately after a 13 also do not count.


My original answer to the problem:

def sum13(nums):
  sum = 0
  for idx,val in enumerate(nums):
    if val == 13 or (idx != 0 and nums[idx-1] == 13):
      pass
    else:
      sum = sum + val

  return sum    


Doing this with list comprehension,  I came up with 

return sum([x if x!=13 and nums[idx-1 if idx &gt;0 else 0] !=13 else 0 for idx,x in enumerate(nums)])


Is there a way to make this cleaner?
EDIT: As pointed out by an anonymous user, my first version did not skip numbers that follow an even number of 13's.

Use an iterator. While you for loop over an iterator you can skip items with next.

def lucky_nums(nums):
    nums = iter(nums)
    for i in nums:
        if i == 13:
            while next(nums) == 13:
                pass
        else:
            yield i

print sum(lucky_nums([12,13,14,15]))