Search code examples
pythontypeerrorsys

python TypeError using sys.stdout.write for array element values


I have a print statement in Python that shows the value and length of elements in an array. I then need to do the same thing using sys.stdout.write instead of print, however am getting the below error.

The original code using print:

import sys
words = ["Madagascar", "Russia", "Antarctica", "Tibet", "Mongolia"]
for w in words:
    print(w, len(w))

Replacing print with sys.stdout.write:

import sys
countries = ["Madagascar", "Russia", "Antarctica", "Tibet", "Mongolia"]
for w in countries:
    sys.stdout.write(countries[w]+" "+len(countries[w]))

The error I get is:

Traceback (most recent call last):
    File "/Users/m/loop.py", line 5, in <module>
    sys.stdout.write(countries[w]+" "+len(countries[w]))
TypeError: list indices must be integers or slices, not str

Solution

  • In a for loop like this, the loop variable takes the value from the list, not its index. In other words, w isn't the index of each country, it's the country itself. Additionally, note that you can't concatenate a string and an int like this, so you'll have to convert the result of len to a string too:

    from sys import stdout
    countries = ["Madagascar", "Russia", "Antarctica", "Tibet", "Mongolia"] # corrected spelling error Antartica -> Antarctica
    for w in countries:
        stdout.write(f"{w} {len(w)}\n") # \n otherwise output will be in the same line (sys.stdout.write ISN'T print which adds \n by default at the end of line.
    

    Shorter version

    from sys import stdout
    countries = ["Madagascar", "Russia", "Antarctica", "Tibet", "Mongolia"]
    [stdout.write(f"{w} {len(w)}\n") for w in countries] # [] are important and for Python 2 compatibility (and some IDEs and REPLs don't support f-strings) you can use **"%s %d" % (w, len(w))** instead of **f"{w} {len(w)}"**