-2

Am asked to create a list with items. Am able to add values to list and determine size, but cannot get user input of index to work. Faulty code inserts given value to end of list and None appears in list in weird index. I've attached a screenshot of the console. Thanks. Edit: Append returns none. adjpos = pos - 1 replaces adjpos = pos + 1

# add an item to the list      
def add():
    i = input("How many items will you add? ")
    i = int(i)
    for element in range(i):
        List.append(input("Add item: "))
    print(List)


def insertItemByPosition():
    pos = int(input("Select insert location: "))
    adjpos = pos + 1

    item = List.append(input("Insert item: "))
    List.insert(adjpos, item)

    print("Revised list: " + str(List))

def main():
    add()    
    insertItemByPosition()
main()

Console: In theory 'Chicken' should be inserted where 'Blue' is located

AMC
  • 2,642
  • 7
  • 13
  • 35
  • 1
    You append to the end of the list. `.append` returns `None`. You then insert this `None` by index (+1 for some reason‽)... – deceze Apr 23 '20 at 20:09
  • What is the issue, exactly? Have you one any debugging? Variable and function names should generally follow the `lower_case_with_underscores` style. Also, please do not share information as images unless absolutely necessary. See: https://meta.stackoverflow.com/questions/303812/discourage-screenshots-of-code-and-or-errors, https://idownvotedbecau.se/imageofcode, https://idownvotedbecau.se/imageofanexception/. – AMC Apr 23 '20 at 21:07
  • Does this answer your question? [Why does append() always return None in Python?](https://stackoverflow.com/questions/16641119/why-does-append-always-return-none-in-python) – AMC Apr 23 '20 at 21:08

1 Answers1

1

In your code you are calling two different methods for adding items to a list. First you call bookList.append() which appends the item to the end of the list. The return value of append() is always None. When you call insert() you are inserting that return value. To fix your code, just remove the call to bookList.append() and assign the return value of the input() to item:

def insertBookByPosition():
    pos = int(input("Select insert location: "))
    adjpos = pos + 1

    item = input("Insert item: ")
    bookList.insert(adjpos, item)

    print("Revised list: " + str(bookList))
jordanm
  • 33,009
  • 7
  • 61
  • 76