Example
A list is a collection of elements, stored in a variable. There are no restrictions on the types of elements stored in the list. The following is a simple example of the list.
students =['bernice','arron','cody']for student in students:print("Hello, "+ student.title()+"!")
Naming and Definition List
Since lists are collections of objects, it is good practice to give them a plural name. If every item in the list is a car, name the list as'cars'. This gives you a direct way to represent the list ('cars'), and ('dog') refers to the list item.
In Python, use square brackets to define a list. As follows:
dogs =['border collie','australian cattle dog','labrador retriever']
Access list elements
The elements in the list are identified by position, starting from zero. Visit the first element in the list as follows:
dogs =['border collie','australian cattle dog','labrador retriever']
dog = dogs[0]print(dog.title())
The number in brackets is the index of the list. Because the list index starts from 0, the index of the list element is always smaller than its position. Therefore Python is called a zero-indexed language (such as C, Java).
So to access the second element, we need to use index 1, and so on.
dog = dogs[1]print(dog.title())
Visit the last element in the list
To access the last element in the list, use index -1.
dog = dogs[-1]print(dog.title())
This syntax can also be used to access the second to last and third to last.
dog = dogs[-2]print(dog.title())
But you cannot use a negative number whose absolute value is greater than the length of the list.
dog = dogs[-4]print(dog.title()
So far, this article on the meaning and usage of lists in python has been introduced. For more information about the contents of lists in python, please search ZaLou.Cn
Recommended Posts