How to add words to a list in Python
To add words to a list in Python, you can use the append()
method. Here's an example:
# Create an empty list
words = []
# Add some words to the list
words.append('hello')
words.append('world')
# Print the list
print(words)
This code will create a list called words
and add the two words hello
and world
to the list. Then it will print the list, which will look like this:
['hello', 'world']
You can also add multiple words to the list at once by using the extend()
method. Here's an example:
# Create an empty list
words = []
# Add multiple words to the list
words.extend(['hello', 'world', 'how', 'are', 'you'])
# Print the list
print(words)
This code will create a list called words
and add the words hello
, world
, how
, are
, and you
to the list. Then it will print the list, which will look like this:
['hello', 'world', 'how', 'are', 'you']
Note that the extend()
method adds each element of the list that you pass to it as a separate element of the original list, whereas the append()
method adds the list itself as a single element of the original list. For example:
# Create an empty list
words = []
# Add a list using the append() method
words.append(['hello', 'world'])
# Print the list
print(words)
This code will create a list called words
and add the list ['hello', 'world']
to the list. Then it will print the list, which will look like this:
[['hello', 'world']]
As you can see, the append()
method adds the list as a single element of the original list, whereas the extend()
method adds each element of the list as a separate element of the original list.