and yet another way of doing it is to use a string method,
.split(), on a string, and you can provide it optionally a separator. That means like a character that you want to split the string on.
I’ll start with the list literal, so I can make a numbers list by writing
numbers = and then opening up square brackets, putting in my values
1, 2, 3, or anything and then closing the square brackets.
And I could even put a tuple in here as well,
(1, 2, 3), and then close the whole list. So this is a valid list. I’ll go ahead and assign it to a variable so that we can look at it a little more.
So the first way to do it, as you’ve seen, is using a list literal: square brackets, comma-separated values in there, values of any type. All right, so the second way that we talked about is using the
You see the square brackets at the beginning and the end, and then it’s strings, single-character strings, separated by commas. Looks very similar to the
tuple() function that you’ve used earlier, and there’s other ways to do it as well.
So from this, you might see that where it split the string is at the space character. So whitespace is the default argument for
.split() to separate a string into kind of words like it’s an approximation for separating strings into words, but you can also pass a separator in there and then get different results.
So if I do the same, but instead of not passing an argument in here and we’re going to put, let’s say a comma, that’s going to be quite similar, then you can see now it’s split on the comma, and that comma that used to be part of
"Hello" is gone because that gets eaten up by splitting it.
I would say that probably the most common way to use this
.split() method is to split on whitespace. So imagine you have a sentence,
"The quick brown fox", and then you call
.split() on it without passing an argument.
So this is probably the most common way of using
.split() to create a list of strings. But you could also specify with, for example, maybe you have comma-separated values and you want to put them into a list, and you could use that
.split() with the comma as the argument.
In this case, the square brackets are not optional, unlike the parentheses are with
tuple(). If you think about it, that makes sense because if you would leave off the square brackets here, then you would create a tuple, right?
Then secondly, we’ve looked at using the built-in
list() function, and there you can pass in a sequence like a string or a tuple. And finally, we’ve looked at using the string method
.split() to create a list from a string,
Become a Member to join the conversation.