python's implementation of creating lists and adding elements to lists

  • 2020-06-19 10:49:32
  • OfStack

Today's lesson is about the list in python.

1. Create lists

1. Create a generic list


>>> tabulation1 = [' The risk ',' tianpeng ',' roller shutters ']
>>> tabulation1
[' The risk ', ' tianpeng ', ' roller shutters ']

>>> tabulation2 = [72,36,18]
>>> tabulation2
[72, 36, 18]

2. Create a mix list


>>> mix tabulation = [' The risk ',72,' tianpeng ',36]
SyntaxError: invalid syntax
>>> mixtabulation = [' The risk ',72,' tianpeng ',36]
>>> mixtabulation
[' The risk ', 72, ' tianpeng ', 36]

3. Create an empty list


>>> empty = []
>>> empty
[]

That's it for you. Now, what do you do if you want to add elements to a list?

2. Add elements to the list

1.append


>>> tabulation1.append(' Purple xia ')
>>> tabulation1
[' The risk ', ' tianpeng ', ' roller shutters ', ' Purple xia ']

2.extend


>>> tabulation1.extend([' Purple xia ',' Green xia '])
>>> tabulation1
[' The risk ', ' tianpeng ', ' roller shutters ', ' Purple xia ', ' Purple xia ', ' Green xia ']

As for the extend method, it is important to note that this method expands the list with a list rather than adding elements directly, so "[]" should be added in "()".

3.insert


>>> tabulation1.insert(1,' Purple xia ')
>>> tabulation1
[' The risk ', ' Purple xia ', ' tianpeng ', ' roller shutters ', ' Purple xia ', ' Purple xia ', ' Green xia ']

Related articles: