In this tutorial, you will learn how to split a list by space in Python. Splitting a list by space is performed when you have a list of strings that contain spaces, and you want to separate them into individual words. This can be useful when processing text data or preparing data for analysis.
Step 1: Create a list of strings
First, you need to create a list of strings that contain spaces. For the purpose of this tutorial, let’s create a simple list:
1 |
string_list = ['Hello World', 'Python Programming', 'Split List By Space'] |
This list contains three strings, and each string contains multiple words separated by spaces.
Step 2: Use list comprehension and the split() function
The next step is to use the split() function and list comprehension to split each string in the list into individual words based on the spaces. The split() function, when called on a string, splits the string into a list of substrings based on the provided delimiter (in this case, a space).
1 |
split_list = [word for string in string_list for word in string.split()] |
We use list comprehension to iterate through each string in the string_list
, and for each string, we call the split()
function to separate the words. Finally, we store the individual words in the split_list
.
Step 3: Print the results
Now we can print the split_list
to see how the strings were separated into individual words:
1 |
print(split_list) |
When you execute the above code, you should see the following output:
['Hello', 'World', 'Python', 'Programming', 'Split', 'List', 'By', 'Space']
Full Code
Here is the complete code for splitting a list by space in Python:
1 2 3 |
string_list = ['Hello World', 'Python Programming', 'Split List By Space'] split_list = [word for string in string_list for word in string.split()] print(split_list) |
And the output will be:
['Hello', 'World', 'Python', 'Programming', 'Split', 'List', 'By', 'Space']
Conclusion
In this tutorial, you’ve learned how to split a list by space in Python using list comprehension and the split()
function. This technique can be helpful in various applications, such as text processing, natural language processing, and data preparation for analysis.