FlavorTownUSA
FlavorTownUSA

Reputation: 11

Python: < not supported between str and int

I'm learning Python through Automate the Boring Stuff and I'm running into a something I don't quite understand.

I'm trying to create a simple for loop that prints the elements of a list in this format: W, X, Y, and Z.

My code looks like the following:

spam = ['apples', 'bananas', 'tofu', 'cats']

def printSpam(item):
    for i in item:
        if i < len(item)-1:
            print (','.join(str(item[i])))
        else:
            print ("and ".join(str(item[len(item)-1])))
    return

printSpam(spam)

I get this error in response:

Traceback (most recent call last):
  File "CH4_ListFunction.py", line 11, in <module>
    printSpam(spam)
  File "CH4_ListFunction.py", line 5, in printSpam
    if i < len(item)-1:
TypeError: '<' not supported between instances of 'str' and 'int'

Any help is appreciated. Thanks for helping a newbie.

Upvotes: 0

Views: 13487

Answers (1)

Tobia Tesan
Tobia Tesan

Reputation: 1936

Ah, but for i in array iterates over each element, so if i < len(item)-1: is comparing a string (the array element item) and an integer (len(item)-1:).

So, the problem is you misunderstood how for works in Python.

The quick fix?

You can replace your for with for i in range(len(array)), as range works like this:

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Thus obtaining:

spam = ['apples', 'bananas', 'tofu', 'cats']

def printSpam(item):
    for i in range(len(item)):
        if i < len(item)-1:
            print (','.join(str(item[i])))
        else:
            print ("and ".join(str(item[len(item)-1])))
    return

printSpam(spam)

The output probably won't be what you expect, though, as 'c'.join(array) uses 'c' as "glue" between the various elements of the array - and what is a string, if not an array of chars?

>>> ','.join("bananas")
'b,a,n,a,n,a,s'

Thus, the output will be:

a,p,p,l,e,s
b,a,n,a,n,a,s
t,o,f,u
cand aand tand s

We can do better anyway.

Python supports so-called slice notation and negative indexes (that start at the end of the array).

Since

>>> spam[0:-1]
['apples', 'bananas', 'tofu']
>>> spam[-1]
'cats'

We have that

>>> ", ".join(spam[0:-1])
'apples, bananas, tofu'

And

>>> ", ".join(spam[0:-1]) + " and " + spam[-1]
'apples, bananas, tofu and cats'

Therefore, you can write your function as simply

def printSpam(item):
    print ", ".join(item[0:-1]) + " and " + item[-1]

That's it. It works.

P.S.: One las thing about Python and array notation:

>>> "Python"[::-1]
'nohtyP'

Upvotes: 5

Related Questions