Aus
Aus

Reputation: 49

How do I unpack a list of lists?

In Python 3 I'm trying to unpack a list of lists:

members = [['3', '5', '5', '20', 'D'], ['2', '2', '2', '30', 'C']]

I want it to print in the format of

3 5 5 20 D
2 2 2 30 C

I've tried using print (' '.join(members)), but I keep getting the error:

TypeError: sequence item 0: expected str instance, list found

Upvotes: 4

Views: 6133

Answers (6)

Vatsal Parekh
Vatsal Parekh

Reputation: 264

This worked

for member in members:
    print " ".join(member)

Upvotes: 2

6502
6502

Reputation: 114491

In python

" ".join(["a", "b", "c"])

produces

"a b c"

If you want a single string as result for your data what you can do is simply nesting two of these expressions:

result = "\n".join(" ".join(L) for L in members)

separating with a newline "\n" elements obtained by separating with space " " items in each list.

If you just want print the data however a simple loop is easier to read:

for L in members:
    print(" ".join(L))

Upvotes: 2

Will
Will

Reputation: 24699

As this is a nested list, when you do:

print (' '.join(members))

You're really trying to join each "sublist" using a space. The error you're seeing is because Python is unable to convert the whole "sublist" to a string. You're on the right track, though!

You could do this using a list comprehension:

print(*[' '.join(m) for m in members], sep="\n")

Or a generator expression:

print(*(' '.join(m) for m in members), sep="\n")

Or a loop:

for member in members:
    print(*member)

Or also in a loop:

for member in members:
    print(' '.join(member))

The * operator unpacks a list into comma-separated arguments (to put it in simple terms).

Upvotes: 4

Sushant
Sushant

Reputation: 324

members = [['3', '5', '5', '20', 'D'], ['2', '2', '2', '30', 'C']]
for item in members:
    print ' '.join(item)

Upvotes: 4

Moses Koledoye
Moses Koledoye

Reputation: 78556

You can unpack the inner list in your print

for member in members:
      print(*member)
# 3 5 5 20 D
# 2 2 2 30 C

Upvotes: 2

TigerhawkT3
TigerhawkT3

Reputation: 49318

You need to act on each member of members in some way. Here are a couple options to start you off.

Iterate over each member and unpack it:

>>> for m in members: print(*m)
...
3 5 5 20 D
2 2 2 30 C

Join each member and unpack the whole thing:

>>> print(*(' '.join(m) for m in members), sep='\n')
3 5 5 20 D
2 2 2 30 C

Upvotes: 2

Related Questions