以下是一个简单的 Python 列表使用示例:

# 创建一个列表
my_list = ['apple', 'banana', 'cherry']

# 输出整个列表
print(my_list)

# 访问列表元素
print(my_list[0]) # 输出:'apple'
print(my_list[1]) # 输出:'banana'
print(my_list[2]) # 输出:'cherry'

# 修改列表元素
my_list[1] = 'orange'
print(my_list) # 输出:['apple', 'orange', 'cherry']

# 添加元素到列表末尾
my_list.append('grape')
print(my_list) # 输出:['apple', 'orange', 'cherry', 'grape']

# 插入元素到列表指定位置
my_list.insert(1, 'pear')
print(my_list) # 输出:['apple', 'pear', 'orange', 'cherry', 'grape']

# 删除列表元素
my_list.remove('orange')
print(my_list) # 输出:['apple', 'pear', 'cherry', 'grape']

# 列表长度
print(len(my_list)) # 输出:4

以上代码演示了如何创建、访问、修改、添加、插入和删除列表元素,以及获取列表长度。

python写一个列表使用

原文地址: https://www.cveoy.top/t/topic/91a 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录