列表基础
1.列表访问
infos=["hello","world","python"]
正向索引 | 0 | 1 | 2 |
---|
列表数据 | hello | world | python |
反向索引 | -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"
print(infos)
"""运行结果
['Hello', 'world', 'python']
"""
5.列表遍历
使用for遍历列表
infos=["hello","world","python"]
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']
"""