How to Append String to Beginning Of List Python

Published on Aug. 22, 2023, 12:16 p.m.

To append a string to the beginning of a list in Python, you can use the insert() method or the + operator.

Using the insert() method:

my_list = ['world']
my_list.insert(0, 'hello')
print(my_list)  # Output: ['hello', 'world']

In this example, we first create a list my_list containing the string 'world'. We then use the insert() method of the list to add the string 'hello' to the beginning of the list. The insert() method takes two arguments: the index where you want to insert the element (in this case, 0 to insert at the beginning of the list), and the element to be inserted.

Using the + operator:

my_list = ['world']
my_list = ['hello'] + my_list
print(my_list)  # Output: ['hello', 'world']

In this example, we first create a list my_list containing the string 'world'. We then combine the string 'hello' with the list using the + operator, which creates a new list. We assign this new list to the variable my_list to overwrite the original list.

Using either method will result in a list with the string appended to the beginning.

Tags:

related content