pythonlist-comprehension

TypeError: sequence item 0: expected str instance, int found. what should I do to show this list as a matrix form


matrix1=[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]

m2="\n".join(["\t".join([ritem for ritem in item]) for item in matrix1])

print(m2)

where am i wrong that i receive this error?


Solution

  • The values you try to join with str.join must be strings themselves. You're trying to join ints and this is causing the error you're seeing.

    You want:

    m2 = "\n".join(["\t".join([str(ritem) for ritem in item]) for item in matrix1])
    

    Note that you can pass any iterable, and not just a list, so you can remove some extraneous [ and ] to create generator expressions rather than list comprehensions.

    "\n".join("\t".join(str(ritem) for ritem in item) for item in matrix1)
    

    Or even just:

    "\n".join("\t".join(map(str, item)) for item in matrix1)