Why is it string join list instead of list join string

0 votes

This has always confused me. It seems like this would be nicer:

my_list = ["Hello", "world"]
print(my_list.join("-"))
# Produce: "Hello-world"

Than this:

my_list = ["Hello", "world"]
print("-".join(my_list))
# Produce: "Hello-world"

Is there a specific reason it is like this?

Dec 2, 2020 in Python by Roshni
• 10,440 points
47 views

1 answer to this question.

0 votes

It's because any iterable can be joined (e.g, list, tuple, dict, set), but its contents and the "joiner" must be strings.

For example:

'_'.join(['welcome', 'to', 'Edureka'])
'_'.join(('welcome', 'to', 'Edureka'))
'welcome_to_Edureka'

Using something other than strings will raise the following error:

TypeError: sequence item 0: expected str instance, int found
answered Dec 2, 2020 by Gitika
• 65,870 points

Related Questions In Python

0 votes
1 answer

Python join: why is it string.join(list) instead of list.join(string)?

950down voteaccepted It's because any iterable can be ...READ MORE

answered May 15, 2018 in Python by aryya
• 7,440 points
211 views
0 votes
1 answer

Is it enough to only create checksum of a zip package instead of each file?

I assume you are asking about the ...READ MORE

answered May 8, 2019 in Python by SDeb
• 13,270 points
737 views
+1 vote
2 answers

Replace every character of string by character whose ASCII value is K times more than it

Refer below code for your problem statement def ...READ MORE

answered May 17, 2020 in Python by Kumar Sambhawam

edited May 18, 2020 by Gitika 6,642 views
0 votes
1 answer

Join all strings in a list of strings

s = " ".join(myList) #here " " ...READ MORE

answered May 30, 2018 in Python by Nietzsche's daemon
• 4,260 points
101 views
0 votes
1 answer

Python join: why is it string.join(list) instead of list.join(string)?

This is because join is a "string" ...READ MORE

answered Jul 30, 2018 in Python by Priyaj
• 58,120 points
248 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 2,047 views
0 votes
0 answers
0 votes
1 answer

String is immutable data type. String.replace() So why there is command for string to replace the values....??

Hey, @Nelson, replace() actually returns a *copy* of ...READ MORE

answered Mar 30, 2020 in Python by Gitika
• 65,870 points
761 views