1

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?

Sachin S
  • 396
  • 8
  • 17

3 Answers3

7

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.

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
  • @Ashwini yeah... sometimes quite painful having to use `print` as a statement :-( – Jon Clements Jun 22 '13 at 15:07
  • if nothing else should be done with result this is the best solution – oleg Jun 22 '13 at 19:08
  • @Jon and oleg: Well, it seems to *me* tricky. I was thinking about `print` being just a replacement for the later processing of items. I do not know. Possibly... *"Explicit is better than implicit."* – pepr Jun 22 '13 at 20:51
3

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))
oleg
  • 4,082
  • 16
  • 16
  • That's a comprehension, not a generator. – Mel Nicholson Jun 22 '13 at 14:50
  • `str.join` converts the genexp into a list first before actually joining them. http://stackoverflow.com/a/9061024/846892 – Ashwini Chaudhary Jun 22 '13 at 14:50
  • this is internal implementation of join as I understand. `":".join(str(i) for i in elem)` itself is generator – oleg Jun 22 '13 at 14:52
  • @oleg: More precisely, the `str(i) for i in elem` is a generator expression. It is used as an argument of `.join()`, this way, the extra parentheses need not to be used. Anyway, the `g = (str(i) for i in elem)` defines a generator named `g`, and then one can write `print(":".join(g))` just after the `g = ...` (the same indentation). The `str.join()` method accepts any iterable that returns strings. Because of that, it can consume also a generator or a generator expression. – pepr Jun 22 '13 at 17:19
1

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
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504