||
Data structures:
1, numbers
2, strings,
3, lists,
4, tuples,
5, dictionaries
This part concerns the list data type.
A list is a vector contains multiple values, including numbers, strings and/or lists. Differing from Matlab in which the elements are bracketed by (), Python brackets the ordered elements by []. In the list of Python, each element is seperated by ','. In order to find an element of a list, the concept index is proposed. The number of index starts from 0.
Example-1
animal=['cat','dog','fish','elephant']
animal[0]
---
outPut
'cat'
NB-1: if the value of the index equals or is larger than the total number of elements of a list, it will cause IndexError.
animal[5]
---
outPut
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
animal[5]
IndexError: list index out of range
NB-2: The index can be negative. In that cases, the value -1 refers to the last index in a list.
NB-3: A slice can get several values of a list. It starts from the first index and ends but excludes the second index.
Example:
animal[0:2]
['cat','dog']
animal[0:-1]
['cat','dog','fish']
animal[1:]
['dog','fish','elephant']
animal[:]
['cat','dog','fish','elephant']
NB-4: list concatenation and list replication
[1,2,3]+['cat','dog','fish','elephant']
[1,2,3,'cat','dog','fish','elephant']
['cat','dog','fish','elephant']*3=['cat','dog','fish','elephant','cat','dog','fish','elephant','cat','dog','fish','elephant']
NB-5: remove values from a list
Example:
animal=['cat','dog','fish','elephant']
del animal[2]
animal
---
outPut
['cat','dog','elephant']
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2024-10-19 22:44
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社