python 变量列表_python变量和列表的用法整理

e60fea99cc411b5e29eb080e176cdfc2.png

1、变量

在Python中使用变量时,不需要定义变量类型。使用方法可参考以下示例。var_1 = 2021

var_2 = "Happy New Year!"

print("This is " + str(var_1))

print(var_2)

2、列表

如果要修改列表中的某个元素,直接根据列表名称和元素对应的索引重新赋值;如果要在列表末尾添加元素,可以直接使用append()函数。如果要在列表中插入元素,需要使用insert()方法。如果要删除列表中的某个元素,如果知道该元素在列表中的位置,可以直接使用del语句。如果要删除列表末尾的元素,可以直接使用pop()方法。您也可以在pop()方法中输入元素的索引,以删除列表中任何位置的元素。以下示例显示了上述操作的具体用法。cars = ['BMW', 'BENZ', 'Audi', 'Prosche']

print(cars)

cars[0] = 'BYD'

print("cars[0] = 'BYD'         ==> " + str(cars))

#Add element with append

cars.append('Volvo')

print("cars.append('Volvo')    ==> " + str(cars))

#Remove the last element with pop

cars.pop()

print("cars.pop()              ==> " + str(cars))

#Add an element with insert

cars.insert(0, 'Volvo')

print("cars.insert(0, 'Volvo') ==> " + str(cars))

#Remove an element with pop

cars.pop(0)

print("cars.pop(0)             ==> " + str(cars))

#Add element with append

cars.append('Volvo')

print("cars.append('Volvo')    ==> " + str(cars))

#Remove an element with del

del cars[3]

print("del cars[3]             ==> " + str(cars))

以上就是python变量和列表的用法整理,希望能对大家有所帮助!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值