Python – Append String to list



Python | Append String to list

Sometimes, while working with data, we can have a problem in which we need to add elements to a container. List can contain any type of data type. Let’s discuss certain ways in which we can perform string append operation in list of integers.

Method #1 : Using + operator + list conversion
In this method, we first convert the string into a list and then perform the task of append using + operator.

# Python3 code to demonstrate working of
# Appending String to list
# using + operator + list conversion
 
# initialize list 
test_list = [1, 3, 4, 5]
 
# initialize string 
test_str = 'gfg'
 
# printing original list 
print("The original list : " + str(test_list))
 
# printing original string 
print("The original string : " + str(test_str))
 
# Appending String to list
# using + operator + list conversion
test_list += [test_str]
 
# printing result
print("The list after appending is : " + str(test_list))

Output :

The original list : [1, 3, 4, 5]
The original string : gfg
The list after appending is : [1, 3, 4, 5, 'gfg']

 

Method #2 : Using append()
This particular function can be used to perform the operation of appending string element to end of list without changing the state of string to list of characters.

# Python3 code to demonstrate working of
# Appending String to list
# using append()
 
# initialize list 
test_list = [1, 3, 4, 5]
 
# initialize string 
test_str = 'gfg'
 
# printing original list 
print("The original list : " + str(test_list))
 
# printing original string 
print("The original string : " + str(test_str))
 
# Appending String to list
# using append()
test_list.append(test_str)
 
# printing result
print("The list after appending is : " + str(test_list))

Output :

The original list : [1, 3, 4, 5]
The original string : gfg
The list after appending is : [1, 3, 4, 5, 'gfg']

 

Last Updated on October 28, 2021 by admin

Leave a Reply

Your email address will not be published. Required fields are marked *

Recommended Blogs

matplotlib.pyplot.imshow() in Pythonmatplotlib.pyplot.imshow() in Python



matplotlib.pyplot.imshow() in Python Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. matplotlib.pyplot.imshow() Function:   The imshow() function in pyplot module of matplotlib library is used