D.Black D.Black - 7 days ago 6
Python Question

My print function from a list returns int values instead of the strings in the list

I am brand new to programming and am working through the "Automate the Boring Stuff" book for Python 3. I've seen several other people with questions on the 'Comma Code' project but not my specific problem. I have come up with a 'working' bit to start off but I can't figure out why my print function gives me int values rather than the strings in the list.

def reList(items):
i = 0
newItems = str()
for items[i] in range(0,len(items)):
newItems = newItems + items[i] + ', '
print(newItems)
i=i + 1

items = ['apples', 'bananas', 'tofu', 'cats']
reList(items)


Thanks!

Answer
def reList(items):
    #i = 0 # no need to initialize it. 
    newItems = str()
    for i in range(0,len(items)): # i not items[i]
        newItems = newItems + items[i] + ', '
        print(newItems)
    #i=i+1 # no need to do 
items = ['apples', 'bananas', 'tofu', 'cats']
reList(items)

range(0,len(items)) returns number 0, 1, 2.. upto len(items) (excluding)

for items[i] in range(0,len(items)) was making items[i] 0, 1, 2...

That's why it was print numbers.

for i in range(0,len(items)) make i as 0, 1, 2... and items[i] gets you item at ith position of the list. So now you get the strings instead of numbers.

A better way would be -

def reList(items):
    newItems = str()
    for it in items:
        newItems = newItems + it + ', '
        print(newItems)
items = ['apples', 'bananas', 'tofu', 'cats']
reList(items)
Comments