1

I've code this code in Python:

if type(data).__name__=='list':
                print type(data).__name__
                print ",".join(data)

And it give me this error:

    print ",".join(data)
exceptions.TypeError: sequence item 0: expected string, list found

How's that possible?!?

Thanks in advance for anyhelp.

0

6 Answers 6

3

You appear to have a list of lists. Try:

",".join(str(x) for x in data)
Sign up to request clarification or add additional context in comments.

Comments

1

str.join() can only join a sequence of strings. Obviously your list contains an item that itself is a list again.

Furthermore, if you really need to check for the type of an object, a better way to do it is

if isinstance(data, list):
    ...

1 Comment

yeah... i'm so dumb... my list contains some lists to... sorry to bother you all. but thanks anyway for the tip about isinstance
0

The first element of data is a list. It must be a string in order for str.join() to work as shown. In fact, all elements must.

Comments

0

Don't explicitly check for types. If you do need to, use isinstance.

The error is appearing because of the contents of data rather than its type. It needs to be a list of strings for the str.join method to work on it.

Comments

0

The first element of your list is also a list, not a string.

Also you don't have to do type(data).__name__=='list' - just type(data) is list

Even better - just check with isinstance since you don't really care about a specific type in most cases.

1 Comment

s/Even better - .*/Even better - just don't check types at all./ ;)
0

join expects an iterable of strings. What seems to happen in your case is that the first element of your list is another list. This is what's causing the error.

As an aside, the if type(data).__name__=='list': ... is as un-Pythonic as code gets.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.