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 trialaa114
1,697 PointsHow add_to_list() function works in shopping list take 3 video of Kenneth love
def add_to_list(item):
if shopping_list:
position = input("Where should i add {}"
"Press Enter to add to the end of the list"
"> ".format(item))
else:
position = 0
try:
position = abs(int(position))
except ValueError:
position = None
if position is not None:
shopping_list.insert(position-1, item)
else:
shopping_list.append(new_item)
Hello !
- if i run this function for the first time when the shopping_list variable is empty the part "if position is not None" will work. Then the index of the first item is actually [-1]. Is my logic true?
- The part "if position is not None" will work in 2 cases: a. when the shopping list is not empty and the user enters a position. b. when the position is 0/ the first item of the list and the part "else: shopping_list.append(new_item)" will work if: a. Value error is my understanding correct?
Thanks all
1 Answer
Chris Freeman
Treehouse Moderator 68,441 PointsYour understanding is correct.
- Notice that
position
is 0 when the user enters "0" or if the list is empty. In either case, the item is inserted at index[-1]
which is the same as an append! - If there is a problem with the conversion of the position to a positive integer, then position becomes
None
and the item is also appended to the list. - If the position provided is larger than the list length,
insert
converts this to an append.
Post back if you have more questions. Good luck!
<noob />
17,062 Points<noob />
17,062 PointsChris Freeman How excatly insert converts the position to an append? is it a default behavior?
Chris Freeman
Treehouse Moderator 68,441 PointsChris Freeman
Treehouse Moderator 68,441 Pointsbot .net, in the Python documents please see
list.
insert(i, x):"
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
"The following are all equivalent: