Strings are one of the most commonly used data types in programming. Using it you can store and manipulate text-based information.
But while working with strings, there can be a case when you might need to append one string to the existing list of strings. Appending a string is an easy process, but there are different methods you can use to append the strings.
In this tutorial, you will know all the methods to append a string to existing list of strings.
Methods to Append a String to the Existing List of Strings
Method 1. Using the append() method
The append() function in Python used to insert an element at the end of the existing list. The argument given is the item to be added can be a string, integer, float, etc.
sample_strings = ["a", "b","c"]
sample_strings.append("d")
print(sample_strings)
Output
["a", "b", "c", "d"]
Method 2. Append the list Using the += operator
You can also use the += operator to append the string to the existing list. Execute the below lines of code.
sample_strings = ["a", "b", "c"]
sample_strings+= ["d"]
print(sample_strings)
Output
["a", "b", "c", "d"]
Method 3. Use the extend() method
The extend() function in Python is a built-in function for lists. It allows you the addition of more than one element to the end of a list. The items you want to be added can be put in a list, tuple, or any other iterable object.
sample_strings = ["a", "b", "c"]
sample_strings .extend(["d"])
print(sample_strings)
Output
["a", "b", "c", "d"]
Method 4 . List concatenation
In Python, merging two or more lists into a single list is referred to as list concatenation, and it can be done using the + operator.
sample_strings = ["a", "b", "c"]
sample_strings= sample_strings+ ["d"]
print(sample_strings)
Output
["a", "b", "c", "d"]
Method 5. List comprehension
Generating a new list in Python using list comprehension is an easy way to do so. It allows you to create a list by executing a single operation or expression on iterable elements such as an existing list or set.
sample_strings = ["a", "b", "c"]
sample_strings = [sample_strings +"!" for string in sample_strings ]
print(sample_strings )
Output
["a", "b", "c", "d"]
Method 6. Using the insert() method
Python has a built-in insert() method that allows you to insert an item at a certain index. This requires two parameters one is the index where the item should go and the item itself.
sample_strings = ["a", "b", "c"]
sample_strings .insert(len(sample_strings ),"d")
print(sample_strings )
Output
["a", "b", "c", "d"]
Conclusion
Appending a string to the existing list of strings is a very easy task if you know all these methods. You can use append(), insert(), extend, list comprehension e.t.c to append a string or list of strings. You can use any one of the methods as per convenience. Most of the coders use the append() function to append string therefore I will also suggest you use this method also.
Leave a Reply