Reputation: 396
I want to print list of list in python 3.x with below code, but it is giving an error.
lol=[[1,2],[3,4],[5,6],['five','six']]
for elem in lol:
print (":".join(elem))
# this is the error I am getting-> TypeError: sequence item 0: expected str instance, int found
I am expecting this output:
1:2
3:4
5:6
five:six
I could achieve the same output using below perl code (this is just for reference):
for (my $i=0;$i<scalar(@{$lol});$i++)
{
print join(":",@{$lol->[$i]})."\n";
}
How do I do it in python 3.x?
Upvotes: 1
Views: 883
Reputation: 142106
I'd go for:
for items in your_list:
print (*items, sep=':')
This takes advantage of print
as a function and doesn't require joins or explicit string conversion.
Upvotes: 7
Reputation: 4182
One can't join int
's only strings. You can Explicitly cast to str
all your data
try something like this
for elem in lol:
print (":".join(map(str, elem)))
or with generator
for elem in lol:
print (":".join(str(i) for i in elem))
or You can use format
instead of casting to string (this allows You to use complex formatting)
for elem in lol:
print (":".join("'{}'".format(i) for i in elem))
Upvotes: 3
Reputation: 250871
Use a list comprehension
and str.join
:
Convert the integers to string(using str()
) before joining them
>>> lis = [[1,2],[3,4],[5,6],['five','six']]
>>> print ("\n".join([ ":".join(map(str,x)) for x in lis]))
1:2
3:4
5:6
five:six
or:
>>> print ("\n".join([ ":".join([str(y) for y in x]) for x in lis]))
1:2
3:4
5:6
five:six
Upvotes: 1