How do you store words in a list in Python?
To store words in a list in Python, you can use the list()
function to create a new list and then use the append()
method to add words to the list. Here is an example:
words = [] # Create an empty list
# Add some words to the list
words.append('cat')
words.append('dog')
words.append('fish')
print(words) # Print the list of words
This code will create a list called words
and add the words cat
, dog
, and fish
to the list. When you run the code and print the words
list, it will output the following:
['cat', 'dog', 'fish']
You can also use the extend()
method to add multiple words to a list at once, like this:
words = [] # Create an empty list
# Add some words to the list
words.extend(['cat', 'dog', 'fish'])
print(words) # Print the list of words
This code will do the same thing as the previous example, but it will use the extend()
method instead of the append()
method to add the words to the list. When you run the code and print the words
list, it will output the same thing:
['cat', 'dog', 'fish']
You can also use the square bracket notation to create a list and add words to it at the same time, like this:
words = ['cat', 'dog', 'fish'] # Create a list and add words to it
print(words) # Print the list of words
This code will create a list called words
and add the words cat
, dog
, and fish
to the list in one step. When you run the code and print the words
list, it will output the following:
['cat', 'dog', 'fish']
Overall, there are several different ways to store words in a list in Python, and the method you choose will depend on your specific needs and preferences.