Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (12.7k points)

This actually confused me a lot. The below code is better:

my_list = ["Hello", "world"]

print(my_list.join("-"))

# Produce: "Hello-world"

than:

my_list = ["Hello", "world"]

print("-".join(my_list))

# Produce: "Hello-world"

I just want to know, whether is there any reason for being like this?

1 Answer

0 votes
by (26.4k points)

This is because that any iterable can be combined (e.g, list, tuple, dict, set), however, its substance and the "joiner" should be strings

Example:

'_'.join(['welcome', 'to', 'stack', 'overflow'])

'_'.join(('welcome', 'to', 'stack', 'overflow'))

'welcome_to_stack_overflow'

When you try to use other than string, it will raise the accompanying error:

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

Interested to learn the concepts of Python in detail? Come and join the python course to gain more knowledge in Python

Watch this video tutorial, if you want to gain more information

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...