list2.py remove_adjacent

56 views
Skip to first unread message

Noah Kaplan

unread,
Nov 3, 2017, 1:42:56 PM11/3/17
to Python GCU Forum
Here's the remove_adjacent challenge and my solution so far:

# D. Given a list of numbers, return a list where
# all adjacent == elements have been reduced to a single element,
# so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or
# modify the passed in list.

def remove_adjacent(nums):
  for n in nums:
    i = nums.index(n)
    if nums[i]==nums[i+1]:
      nums = nums.remove(n)
  return nums

What I am trying to do is to iterate over the list 'nums' checking if each element is the same as the next one.  If it is, the first appearance is removed so that the for loop will still check the next one.

The problem is the line 'i = nums.index(n)' is throwing off this error: AttributeError: 'NoneType' object has no attribute 'index'

If 'nums' is defined as a list, why can't I use 'nums.index(n)' to get the index for each item n?

Thanks for any help.

Joe Bloggs

unread,
Nov 5, 2017, 7:32:47 PM11/5/17
to Python GCU Forum
I think the error you are getting has to do with a) overshooting the end of the list with your n+1, and b) removing items from a list that you are traversing left to right. I think the better solution would be to create an empty list that you add non-repeating numbers to. You can then return this list. You will need to make sure you stop checking your numbers at list length minus 1 to prevent over-shooting with your n+1 indexing.

Joe
Reply all
Reply to author
Forward
0 new messages