To add a string to a list in Python, the easiest way is to use the Python list append() function.
string = "string"
lst = ["a", "b", "c"]
lst.append(string)
print(lst)
#Output:
["a", "b", "c", "string"]
You can also wrap a string in square brackets and use the concatenation operator + to add a string to a list.
string = "string"
lst = ["a", "b", "c"]
lst = lst + [string]
print(lst)
#Output:
["a", "b", "c", "string"]
When working with collections of data, the ability to add and remove items from your collection easily is very valuable.
One such case is if you want to add a string to a lits of objects in Python.
To add a string to a list in Python, the easiest way is to use the Python list append() function.
Below is a simple example showing you how to add a string to a list in Python.
string = "string"
lst = ["a", "b", "c"]
lst.append(string)
print(lst)
#Output:
["a", "b", "c", "string"]
Using + operator to Add String to List in Python
Another way you can add a string variable to a list is with the Python concatenation operator +.
To use +, you should wrap the string variable in square brackets to convert it to a list and then add it to a list as shown below.
string = "string"
lst = ["a", "b", "c"]
lst = lst + [string]
print(lst)
#Output:
["a", "b", "c", "string"]
Hopefully this article has been useful for you to learn how to add a string to a list in Python.