0

Since I don't want an array's indices to be separated by a comma, I wrote this code:

landscape2 = ''.join(landscape)

However, I got an error message saying "landscape2 = ''.join(landscape) TypeError: sequence item 0: expected str instance, list found" I don't know what this means, and I wondered if you could help.

Kyle
  • 53
  • 6
  • 2
    It means at least one element is a list inside your list i.e `[["foo"]]`, if you want to also join what is inside the lists,you want something like `landscape2 = ''.join(map("".join,landscape))`. If you posted your code and the error it would be a lot easier to diagnose – Padraic Cunningham Mar 30 '16 at 23:10
  • 1
    Show what landscape is – joel goldstick Mar 30 '16 at 23:12
  • landscape = [['-,-,-,-,-,-,-,-,-,-,-,-,-,-,X'] ,['-,-,-,-,-,-,-,-,-,-,-,-,-,-,-'] ,['-,-,-,-,-,-,-,-,-,-,-,-,-,-,-'] ,['-,-,-,-,-,-,-,-,-,-,-,-,-,-,-'] ,['-,-,-,-,-,-,-,-,-,-,-,-,-,-,-'] ,['-,-,-,-,-,-,-,-,-,-,-,-,-,-,-'] ,['-,-,-,-,-,-,-,-,-,-,-,-,-,-,-'] ,['-,-,-,-,-,-,-,-,-,-,-,-,-,-,-'] ,['-,-,-,-,-,-,-,-,-,-,-,-,-,-,-'] ,['-,-,-,-,-,-,-,-,-,-,-,-,-,-,-'] ,['-,-,-,-,-,-,-,-,-,-,-,-,-,-,-'] ,['-,-,-,-,-,-,-,-,-,-,-,-,-,-,-'] ,['-,-,-,-,-,-,-,-,-,-,-,-,-,-,-'] ,['-,-,-,-,-,-,-,-,-,-,-,-,-,-,-'] ,['O,-,-,-,-,-,-,-,-,-,-,-,-,-,-']] – Kyle Mar 30 '16 at 23:15
  • TypeError: list indices must be integers, not str – Kyle Mar 30 '16 at 23:16
  • Yep, you want what I suggested above, if you want each on a newline use `"\n"` for the outer join, if you want one long line leave it as is – Padraic Cunningham Mar 30 '16 at 23:16

1 Answers1

0

The error you described means it's trying to join two lists together. That's not possible.

Based on your comment, it sounds like what you ACTUALLY want to do is:

"\n".join(["".join(sublst) for sublst in landscape])

This will create a new list of strings, then join those strings with newlines, essentially creating a 2D rectangle of characters.

Adam Smith
  • 52,157
  • 12
  • 73
  • 112
  • you can remove the list comprehension, it will just use generator comprehension instead – Tadhg McDonald-Jensen Mar 30 '16 at 23:18
  • 2
    @TadhgMcDonald-Jensen, that is less efficient than using a list – Padraic Cunningham Mar 30 '16 at 23:20
  • 1
    @TadhgMcDonald-Jensen see the accepted answer to [this question](http://stackoverflow.com/questions/245792/when-is-not-a-good-time-to-use-python-generators). It's over a year old, but I haven't seen any evidence that it's changed (admittedly I haven't profiled it in *forever*) – Adam Smith Mar 30 '16 at 23:20
  • @TadhgMcDonald-Jensen essentially, `str.join` likes lists, since it has two make two passes anyway. – Adam Smith Mar 30 '16 at 23:20