Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (2016, retired 2019) Lists Shopping List Take Three

My take on fixing ZERO position

Hello everyone.

I wanted to share my code solving the problem if the user enter index #Zero In the original code if '0' is used the function would deduct '1' and you would have index '-1'

try:
    position = abs(int(position))
    if position == False:
      raise ValueError
  except ValueError:
    position = None
  if position is not None:
    shopping_list.insert(position - 1, item)
  else:
    shopping_list.append(new_item)
  show_list()

I hope it helps.

nakalkucing
nakalkucing
12,964 Points

Neat! I haven't tested it yet, but it looks like a neat concept.

1 Answer

Steven Parker
Steven Parker
231,275 Points

Wouldn't inserting something at the -1 position make it second to last (when you want it to be first)?

No it cannot be since you are taking the absolute of any given location.

position = abs(int(position))
Steven Parker
Steven Parker
231,275 Points

I was talking about the calculation performed when a "0" is entered. As you said, "if '0' is used the function would deduct '1' and you would have index '-1'". It's that -1 that you pass on to "insert" that would place the item at the second-to-last position.

Oh no, i'm raising a value error and excepting it to set position to None.

Steven Parker
Steven Parker
231,275 Points

Oh, I get it. Comparing a numeric value to "False" was a bit confusing. And the indentation seems off ("try" and "except" should always line up).

Now that I understand what's happening, you could condense it a bit:

try:
  position = abs(int(position))
except ValueError:
  position = 0
if position > 0:
  shopping_list.insert(position - 1, item)
else:
  shopping_list.append(new_item)
show_list()

Thank you Steven, you are a blessing :)