python basics-list

巴扎黑
Release: 2016-12-03 09:43:34
Original
1089 people have browsed it

1. List creation

new_list1 = ['TV','Car','Cloth','Food']
new_list2 = list(['TV','Car','Cloth','Food'])
print (new_list1)
print (new_list2)
Operating results:
['TV', 'Car', 'Cloth', 'Food']
['TV', 'Car', 'Cloth', 'Food']

2. List commonly used methods:

1. append

new_list1 = ['TV','Car','Cloth','Food']
print (new_list1)
new_list1.append('Water') # Append 'water'
print (new_list1)
Operating results:
['TV', 'Car', 'Cloth', 'Food']
['TV', 'Car', 'Cloth', 'Food', ' Water']

2.count

new_list1 = ['TV','Car','Cloth','Food','Food']
print (new_list1.count('Food')) #Statistics'food 'Number of times in the list => 2 times

3.extend

new_list1 = ['TV','Car','Cloth','Food','Food']
new_list1.extend([11, 22,33,'Car'])
print (new_list1)
Operating results:
['TV', 'Car', 'Cloth', 'Food', 'Food', 11, 22, 33, 'Car']

4.sort

new_list1 = ['TV','Car','Cloth','Food','Food']
print (new_list1)
new_list1.sort() #Forward sort
print (new_list1 )
new_list1.sort(reverse=True) #Reverse sort
print (new_list1)
Operating results:
['TV', 'Car', 'Cloth', 'Food', 'Food']
['Car' , 'Cloth', 'Food', 'Food', 'TV'] #Forward sorting results
['TV', 'Food', 'Food', 'Cloth', 'Car'] #Reverse sorting results

5. len

new_list1 = ['TV','Car','Food','Cloth','Food']
print (len(new_list1)) => 5 #Print the number of elements

6.remove

new_list1 = ['TV','Car','Food','Cloth','Food']

new_list1.remove('Food')
print (new_list1)
Run result:
[ 'TV', 'Car', 'Cloth', 'Food'] #remove will delete the first identical element found

7.pop

new_list1 = ['TV','Car','Food', 'Cloth','Food']
new_list1.pop() #Delete an element randomly
print (new_list1)
new_list1.pop(2) #Specify to delete an element
print (new_list1)
The operation result is:
[' TV', 'Car', 'Food', 'Cloth']
['TV', 'Car', 'Cloth'] #, what is deleted here is the third element 'Food'

8.index

new_list1 = ['TV','Car','Food','Cloth','Food']
print (new_list1.index('Food')) #Return the index value of the specified element, and return the found element for the same element The first
running result is: 2

9.insert

new_list1 = ['TV','Car','Food','Cloth','Food']
new_list1.insert(2,'HAHAHA' ) #Insert element into the specified position
print (new_list1)
The operation result is:
['TV', 'Car', 'HAHAHA', 'Food', 'Cloth', 'Food']


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template