If you want to append a string to a list, you can do it using the append function.
1 2 3 4 5 |
my_list = [1, 2, 3] my_str = 'test' my_list.append(my_str) print("The new list is : " + str(my_list)) |
The string is added to the end of the list. Now the list consists of 3 numbers and one string.
The new list is : [1, 2, 3, 'test']
The Plus (+) Operator
You can achieve a similar effect using the plus operator.
1 2 3 4 5 6 |
my_list = [1, 2, 3] my_str = 'test' my_list += [my_str] print("The new list is : " + str(my_list)) |
If you run the code the result is identical.
The new list is : [1, 2, 3, 'test']
my_list += [my_str] is the same as my_list = my_list + [my_str]. It’s just a shorter notation used in many programming languages, including Python.
Notice that the string is added as the whole list element, that’s why it’s in the square brackets: [my_str].
Append Individual Elements of the String
In the last part of the tutorial, we used brackets to add the string as a single element.
Let’s take a look at what happens if we remove these brackets.
1 2 3 4 5 6 |
my_list = [1, 2, 3] my_str = 'test' my_list += my_str print("The new list is : " + str(my_list)) |
Now, each character of the string is added as a single element.
The new list is : [1, 2, 3, 't', 'e', 's', 't']
Append String to Empty List
If you want to make a list consisting only of the string characters, you can do it by creating an empty list and adding each character separately.
1 2 3 4 5 6 |
my_list = [] my_str = 'test' my_list += my_str print("The new list is : " + str(my_list)) |
Now, there are only string characters inside the list.
The new list is : ['t', 'e', 's', 't']
Use Loop
You can use a loop to append individual characters. For this, we are going to use the for loop and the append function.
1 2 3 4 5 6 7 8 |
my_list = [] my_str = 'test' for character in my_str: my_list.append(character) print(my_list) print("The new list is : " + str(my_list)) |
The for loop goes through each character of the string and adds it to the end of the list.
Inside the loop, the actual value of my_list is printed each time the character is added to the end of the list and the final result is the same as before.
['t'] ['t', 'e'] ['t', 'e', 's'] ['t', 'e', 's', 't'] The new list is : ['t', 'e', 's', 't']