How to Add a String to a List in Python
To add a string to a list in Python, you can use the append() function or the + operator.
The following examples show how to use these methods to add a string to a list in Python.
Use append() Function
We can use the append() function to add a string to a list.
Suppose we have the following list:
# Declare list
Emp_Name = ['Anita', 'Sanika', 'Shubham', 'Gaurav', 'Namita', 'Sushma']
# Declare new string
new_Emp = 'John'
# Add a new name to list
Emp_Name.append(new_Emp)
# Print the updated list of Emp_Name
print("Updated list:", Emp_Name)
Output: 👇️
Updated list: ['Anita', 'Sanika', 'Shubham', 'Gaurav', 'Namita', 'Sushma', 'John']
In this example, we use the append() function to add the string John to the list Emp_Name.
Using + Operator
We can use the + operator to add a string to a list.
Suppose we have the same list as above.
We can use the following code to add the string John to the list:
# Add a new name to list
New_emp = Emp_Name + [new_Emp]
# Print the updated list of New_emp
print("Updated list:", New_emp)
Output: 👇️
Updated list: ['Anita', 'Sanika', 'Shubham', 'Gaurav', 'Namita', 'Sushma', 'John']
In this example, we use the + operator to add the string John to the list Emp_Name and store the result in New_emp.