列表基础(列表访问,列表遍历)

列表基础


1.列表访问

#定义一个列表
infos=["hello","world","python"]
正向索引012
列表数据helloworldpython
反向索引-3-2-1

正向访问列表
#定义一个列表
infos=["hello","world","python"]
print(infos[0])
print(infos[1])
print(infos[2])
"""运行结果
hello
world
python
"""


反向访问列表
#定义一个列表
infos=["hello","world","python"]
print(infos[-1])
print(infos[-2])
print(infos[-3])
"""运行结果
python
world
hello
"""


2.列表长度

#定义一个列表
infos=["hello","world","python"]
//打印列表的长度
print(len(infos))
"""运行结果
3
"""


3.列表索引越界

当访问超出列表索引范围时,会抛出IndexError异常
#定义一个列表
infos=["hello","world","python"]
//访问超出列表的索引
print(infos[3])
"""运行结果
IndexError: list index out of range
"""


4.列表修改指定索引数据

#定义一个列表
infos=["hello","world","python"]
#修改infos列表索引为0的数据,改为Hello
infos[0]="Hello"
#打印infos列表
print(infos)
"""运行结果
['Hello', 'world', 'python']
"""


5.列表遍历


使用for遍历列表
#定义一个列表
infos=["hello","world","python"]
#for遍历列表
for info in infos:
    print((info))
"""运行结果
hello
world
python
"""

使用for通过索引遍历列表
#定义一个列表
infos=["hello","world","python"]
#通过索引遍历列表
for i in range(len(infos)):
    print(infos[i])
"""运行结果
hello
world
python
"""


6.列表乘法

#定义一个列表
infos=["hello","world","python"]
#空值列表
nones=[None]
print(infos*3)
print(nones*3)
"""运行结果
['hello', 'world', 'python', 'hello', 'world', 'python', 'hello', 'world', 'python']
[None, None, None]
"""


7.列表加法

#定义两个列表
list1=["A","B","C"]
list2=["D","E","F"]
#两个列表相加
print(list1+list2)
"""运行结果
['A', 'B', 'C', 'D', 'E', 'F']
"""
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值