Python: Lists
Lists
Lists in Python represent ordered sequences of values.
1 | primes = [2, 3, 5, 7] |
Types of things in list
1 | planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune'] |
A list of list
1 | hands = [ |
A list can contains different types of variables
1 | my_favourite_things = [32, 'raindrops on roses', help] |
Indexing
1 | planets[0] |
‘Mercury’
Elements at the end of the list can be accessed with negative numbers, starting from -1:
1 | planets[-1] |
Slicing
What are the first three planets?
前三个行星是什么?
1 | planets[0:3] |
[‘Mercury’, ‘Venus’, ‘Earth’]
The starting and ending indices are both optional. If I leave out the start index, it’s assumed to be 0. So I could rewrite the expression above as:
起始索引和结束索引都是可选的。所以我可以把上面的表达式改写成:
1 | planets[:3] |
[‘Mercury’, ‘Venus’, ‘Earth’]
本部落格所有文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明來自 Codes!