What Are Python Lists? How to Create List in Python?
What are Lists in Python?
Lists are ordered collections of data, similar to arrays, which are defined in other languages. It's particularly adaptable because list elements don't have to be of the same type.
How to Create a List in Python?
You can make a list in Python by simply putting the sequence inside square
List = [ ] print("Initial blank List: ") print(List) # Creating a List with # the use of a String List = ['WSCubeTech'] print("\nList with the use of String: ") print(List) # Creating a List with # the use of multiple values List = ["WS", "Cube", "Tech"] print("\nList containing multiple values: ") print(List) print(List) # Creating a Multi-Dimensional List # (By Nesting a list inside a List) List = [['WS', 'Cube'], ['Tech’']] print("\nMulti-Dimensional List: ") print(List)
Accessing List Elements in Python
You can use the index number in order to retrieve the elements from a list. To go to a specific item in a list, use the index operator . Negative sequence indexes in Python denote positions from the array's end.
It is sufficient to write List[-3] instead of needing to compute the offset as in List[len(List)-3]. The role of negative indexing is to represent starting from the end, where -1 shows the last item, -2 the second-last item, and so on.
Each item in a list has its own index value, which starts at zero. The index values are incremented by one. The index value of an individual item in a tuple can be used to access it.
The index values for the list that we declared before are as follows:
We can now access a single element separately because we know the index values for each item. We may fetch the item with the index value 3 by using the following code:
The output of this code will be Strawberry because it has a value of 3 on the index.
A negative index value is assigned to each item in a list. We can count backward from the end of a list using these values. They begin with a negative value.
If you're working with a big list, a negative index number will be handier. This is because you can work your way backward from the end of the list.
Here are the negative index values for our ice_cream_flavors tuple:
The following code can be used to retrieve the value at the index point of -1:
Here is another example:
Python3 # Python program to demonstrate # accessing of element from list # Creating a List with # the use of multiple values List = ["WS", "Cube", "Tech"] # accessing a element from the # list using index number print("Accessing element from the list") print(List) print(List) # accessing an element using # negative indexing print("Accessing element using negative indexing") # print the last element of list print(List[-1]) # print the third last element of list print(List[-3])