深度阅读

How to Append String to Beginning Of List Python

作者
作者
2023年08月22日
更新时间
11.03 分钟
阅读时间
0
阅读量

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.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。