D.Black
D.Black

Reputation: 23

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!

Upvotes: 2

Views: 130

Answers (2)

themistoklik
themistoklik

Reputation: 880

You can try this

 for i in range(0,len(items)):
     newItems += items[i]
     if i!=len(items)-1:
         newItems += ','

the +=x is like writing newItems = newItems + x

You want to loop for every value of items, and add a comma at the end, except of course in the last step. That's the purpose of the if.

You can also do this in python with join and think of how you can solve your problem in one line. Welcome to Python :)

Upvotes: 1

Shreyash S Sarnayak
Shreyash S Sarnayak

Reputation: 2335

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)

Upvotes: 2

Related Questions