Home >Backend Development >Python Tutorial >Example of list initialization method in Python

Example of list initialization method in Python

高洛峰
高洛峰Original
2017-02-22 16:50:461933browse

This article mainly introduces the list initialization method in Python, analyzes the commonly used methods of list initialization and related usage precautions. Friends in need can refer to the following

The example of this article describes the list initialization method in Python. Share it with everyone for your reference, the details are as follows:

1. Basic method.

lst = [1, 2, 3, 4, 5]

2. Initialize consecutive numbers.

>>> lst = [n for n in range(5, 10)]
>>> print(lst)
[5, 6, 7, 8, 9]

3. Initialize n identical values. (Two ways)

>>> lst = ['x' for n in range(5)]
>>> print(lst)
['x', 'x', 'x', 'x', 'x']
>>> lst = ['z']*5
>>> print(lst)
['z', 'z', 'z', 'z', 'z']
>>> lst = [0]*3
>>> print(lst)
[0, 0, 0]

4. Python’s four data types are dictionary, set, list, and tuple, using curly brackets, square brackets, and small brackets respectively. Brackets indicate. Such as:

字典:dic={'a':12, 'b':34}
集合:s = {1, 2, 3, 4}
列表:li=[1, 2, 3, 3]
元组:tup=(1, 2, 3, 4)  #元组是不可更改的列表


For more related articles about examples of list initialization methods in Python, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn