1. Introduction to the list
A list consists of a series of elements arranged in a particular order. You can create a list of all the letters, numbers 0~9, or names of all family members in the alphabet, or you can add anything to the list, where the elements can have no relationship. Given that a list usually contains multiple elements, it is a good idea to give the list a name that represents a complex number (such as letters , digits, or names ).
python[]
Bicycles = ['trek''Cannondale'redline ' ' Specialized ' ]print(bicycles)
2. Accessing list elements
Bicycles = ['trek''Cannondale'redline ' ' Specialized '
Print (Bicycles[0])
Output: Trek
Python provides a special syntax for accessing the last list element. allows Python to return the last list element by specifying the index as 1
bicycles = [ " trek " , " cannondale ", " redline ", " Specialized " ] Print (bicycles[-1])
The output is: specialized This syntax is useful because you often need to access the last element without knowing the length of the list. This Convention also applies to other negative indexes, for example, index 2 returns the last two list elements, index -3 returns the third-lowest list element, and so on.
You can use each value in the list as you would with other variables. For example, you can use stitching to create a message based on the values in the list.
3. Add an element to the list
3.1 adding elements at the end of the list
motorcycles = [ " honda " , " yamaha ", " suzuki " " print ( Motorcycles) motorcycles.append ( " ducati " ) print (motorcycles)
Method Append () adds the element ' Ducati ' to the end of the list without affecting all other elements in the list:
Output:
[' Honda ', ' Yamaha ', ' Suzuki ']
[' Honda ', ' Yamaha ', ' Suzuki ', ' Ducati ']
3.2 Inserting elements into a list
Use the Insert () method to add a new element anywhere in the list. To do this, you need to specify the index and value of the new element
motorcycles = [ " honda " , " yamaha ", " suzuki " ]motorcycles.insert (0, " ducati " ) print (motorcycles)
In this example, the value ' Ducati ' is inserted at the beginning of the list ; method Insert () adds space at index 0 and stores the value ' Ducati ' in this place. This action adds each element in the list to the right
Move one position:
Output:[' Ducati ', ' Honda ', ' Yamaha ', ' Suzuki ']
3.3 Remove an element from the list
Del statement can be
3.4 Using the Method Pop () to delete an element
Deletes an element of an array and stores it in another array
Python Learning note 2--list