列表
中括号括起,逗号隔开,元素类型不限
subjects = [1, 3.0, 'a', True]
print(subjects[0])
print(subjects[1])
print(subjects[2])
print(subjects[3])
print(type(subjects[0]))
print(type(subjects[1]))
print(type(subjects[2]))
print(type(subjects[3]))
print(type(subjects))
1
3.0
a
True
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
<class 'list'>
打印列表全体
subjects = [2, 0.2, 'True', True]
print(subjects)
[2, 0.2, 'True', True]
列表元素数
numbers = [1, 2, 3]
print(len(numbers))
3
追加元素
numbers = [1, 3, 5]
print(numbers)
numbers.append(7)
print(numbers)
[1, 3, 5]
[1, 3, 5, 7]
插入元素
numbers = [2, 4, 8]
print(numbers)
numbers.insert(2, 6)
print(numbers)
[2, 4, 8]
[2, 4, 6, 8]
移除元素
numbers = [1, 3, 5, 7]
print(numbers)
numbers.remove(5)
print(numbers)
[1, 3, 5, 7]
[1, 3, 7]
移除指定位置的元素
numbers = [1, 3, 5, 7]
print(numbers)
del numbers[1]
print(numbers)
[1, 3, 5, 7]
[1, 5, 7]
确认要素有无
numbers = [1, 3, 5, 7]
n = int(input('输入整数:'))
if n in numbers:
print('在列表中')
else:
print('不在列表中')
输入整数:7
在列表中
字符串转列表
s = input('输入字符串:')
print('转换为列表')
print(list(s))
输入字符串:333
转换为列表
['3', '3', '3']
整数列表
range(start, stop)
计数从 start 开始,不输入start则从 0 开始,到 stop 结束,但不包括 stop
print(type(range(6)))
<class 'range'>
注意range()
的返回值是range型,如果要输出列表则需要用list()
来转换
print(list(range(6)))
[0, 1, 2, 3, 4, 5]