Python-List
Obtain the value
The value is obtained from ‘0’, which means ‘0’ is the first value.
1 | spam=['cat','bat','rat','elephant'] |
1 | spam[0] |
We can also add it to a string:
1 | 'The '+spam[1]+' ate the '+spam[0]+'.' |
The list in the list:
1 | spam=['cat','bat'],[10,20,30,40,50] |
Use negative subscripts to get the value:
1 | spam=['cat','bat','rat','elephant'] |
Obtain the slice
Use range of subscripts (the range includes the former one, but doesn’t include the later one)
1 | spam=['cat','bat','rat','elephant'] |
without one/both subscript(s) (from the beginning or/and the end)
- [:] means the whole list
1 | spam=['cat','bat','rat','elephant'] |
Length
Length is the number of value it has.
1 | spam=['cat','dog','moose'] |
Changing the value by using subscripts
1 | spam=['cat','bat','rat','elephant'] |
The combination and calculation of list
1 | [1,2,3]+['A','B','C'] |
Delete by using del
1 | spam=[1,2,3,4] |
one usage: enter the cats’ name:
1 | catnames=[] |
The processing steps:
Enter the name of cat 1(Or enter nothing to stop.):
Alpha
Enter the name of cat 2(Or enter nothing to stop.):
Bravo
Enter the name of cat 3(Or enter nothing to stop.):
Cathy
Enter the name of cat 4(Or enter nothing to stop.):
The result:
The cat names are:
Alpha
Bravo
Cathy
Use list in loop
1 | supplies=['pen','staplers','flame-throwers','binders'] |
in and not in
example:
1 | 'howdy'in['hello','hi','howdy'] |
usage:
1 | mypet=['Zophie','Pooka','Simon'] |
improve the former usage about the cats’ names:
1 | catnames=[] |
The processing steps:
Enter the name of cat 1(Or enter nothing to stop.):
Alpha
Enter the name of cat 2(Or enter nothing to stop.):
Bravo
Enter the name of cat 3(Or enter nothing to stop.):
Alpha
The name has existed
Enter the name of cat 3(Or enter nothing to stop.):
Cathy
Enter the name of cat 4(Or enter nothing to stop.):
The result:
The cat names are:
Alpha
Bravo
Cathy
Mutiple values:
We can give the list other values.
1 | cat=['fat','black','loud'] |
Other instructions
append: add a new value to the list in the end
1 | spam=[1,2,3,4] |
insert: add a new value in the middle
1 | spam=[1,2,3,4] |
index: show the position of the value
1 | spam=[1,2,3,4] |
remove: remove the value from the list
1 | spam=[1,2,3,4] |
sort: put the value in order
numbers:
1 | spam=[2,5,3.14,1,-7] |
words: (the upper letters are in the front)
1 | spam=['ants','cats','dogs','badgers'] |
reverse: reverse the order of the value
1 | spam=['ants', 'badgers', 'cats', 'dogs'] |
ignore the lower or upper letters:
1 | spam=['b','a','A','z','Z'] |
tuple: (can be read only)
1 | tuple([1,2,3,4]) |
*if turn dictionary to tuple, it will only show the key:
1 | tuple({1:2,3:4}) |