Python | Add line to list

Python Methods and Functions

Method # 1: Using the + operator + list transformation
In this method, we first convert a string to a list and then perform the add task using the + operator.

# Python3 code to demonstrate how it works
# Adding a line to the list
# use + operator + list transform

 
# initialize list

test_list = [ 1 , 3 , 4 , 5 ]

  
# initialize string

test_str = `gfg`

  
# print original list

print ( "The original list:" + str (test_list))

 
# print original line

print ( "The original string:" + str (test_str))

 
# Add a line to the list
# use + operator + list transform

test_list + = [test_str]

 
# print 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 adding a string element to the end of the list without changing the state of the string in the character list .

# Python3 demo code
# Adding a line to the list
# using append ()

 
# initialize the list

test_list = [ 1 , 3 , 4 , 5 ]

 
# initialize string

test_str = `gfg`

  
# print the original list

print ( " The original list: " + str (test_list))

 
# print original line

print ( "The original string:" + str (test_str))

  
# Adding a line to the list
# using append ()
test_list.append (test_str)

 
# print 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`] 




Get Solution for free from DataCamp guru