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 trialRudi Schenck
16,642 Pointsposition -1 example
At the end of the video, Kenneth mentions that the code can be shortened a bit by setting position to -1 and always using append. I can't figure out what he means by this, can anyone post an example? Thanks!
2 Answers
ado
1,719 PointsI think he meant position = -1 instead of None then the if statements are no longer needed which shortens the program. I did try it but it's not adding the item to the end of the list. What worked for me is position = len(shopping_list) + 1.
try:
position = abs(int(position))
except ValueError:
position = len(shopping_list) + 1
shopping_list.insert(position-1, item)
Chris Guy
Python Web Development Techdegree Graduate 14,615 PointsI was also confused by this part, but I did manage to shorten the function slightly and remove the need for 'None' like this:
try:
position = abs(int(position))
except ValueError:
shopping_list.append(new_item)
else:
shopping_list.insert(position - 1, item)