Question re: list.extend

1952
3
Jump to solution
01-26-2016 01:35 PM
KennethKirkeby
New Contributor III

I'm a new Python student. Using a loop, I need to add to a list. The following is not working. Not sure what I'm missing or if my logic is bad.

#Variables

myList = []

item = ''

#Create name list

item = raw_input("Please enter a name or blank to quit: ")

while item <> '':

    myList.extend(item)

printmyList

Traceback (most recent call last):

  File "C:/Users/ken/Desktop/HW4b.py", line 14, in <module>

    myList.extend(item)

MemoryError

Thanks ... Ken

0 Kudos
1 Solution

Accepted Solutions
BillDaigle
Occasional Contributor III
myList = []

item = ''

#Create name list

item = None

while item <> '':
    item = raw_input("Please enter a name or blank to quit: ")
    myList.append(item)
print myList

You need to ask for a new input on each iteration of the loop.

View solution in original post

3 Replies
BillDaigle
Occasional Contributor III
myList = []

item = ''

#Create name list

item = None

while item <> '':
    item = raw_input("Please enter a name or blank to quit: ")
    myList.append(item)
print myList

You need to ask for a new input on each iteration of the loop.

KennethKirkeby
New Contributor III

Had to add the brackets to ITEM or the list was individual letters.

myList = []

Item = 'None'

while item <> '':

    item = (raw_input("Please enter a number (Blank to quit): "))

    myList.extend([item])

printmyList

************************************************************

Please enter a number (Blank to quit): Ken

Please enter a number (Blank to quit): Jim

Please enter a number (Blank to quit): Bill

Please enter a number (Blank to quit):

['Ken', 'Jim', 'Bill', '']

0 Kudos
Luke_Pinner
MVP Regular Contributor

Use .append instead of .extend - paraphrased from the python docs:

list.append(x)

    Add an item to the end of the list;

list.extend(L)

    Extend the list by appending all the items in the given list

i.e append is for adding a single item to the list, extend is for adding multiple items in a list to the list