A list is a collection of items stored in a single variable. A list contains numerous items that are related or different.
In the case of related items, we might decide to store types of animals in a list. Examples include lions, leopards, dogs, pigs, Tse Tse flies, etc. Another version is storing different kinds of items in a list, like pencils, shirts, towels, etc.
What is a python List?
A Python list is a collection of items housed in a square bracket and stored in a variable.
A Python list is a sequence data type, and it is very versatile. So many operations can be carried out on a Python list, which includes slicing, multiplying, looping, adding, indexing, and many more.
Python list can be represented as follows:
list1 = ["James", "John", "Mary", "Vincent"]
list2 = ["Lion", "Ant", 1, 4]
list3 = ["Oxford", True, 34, "Grace", 5.678]
Python list can accommodate items of different data types. The data type can include Booleans, Integers, strings, etc.
How to access python list elements?
Python list elements can be accessed using the index number. The index operator [ ] is used to access an item in a list. The index must be an integer. Nested lists are accessed using nested indexing
lists = ["brain", "Vein", 1, 4.5, 8, True, "single", "Joy", "America", "Nigeria"]
#print second term
print(lists[1]) #Vein
#print fourth term
print(lists[3]) #4.5
#nested_lists
nested_list = [["goat", "ant"], False, ["Dubai", "Lagos", "Rabat"], 5]
#print the third term of the third list
print(nested_list[2][2]) # print Rabat
#print the second term of the first list
print(nested_list[0][1]) # print ant
Using a Negative index to access elements in a list.
In Python, negative sequence indexes represent positions from the end of the array. The last item on the list is -1, the second to the last is -2, and so on.
lists = ["Tongue", "Hand", 4, "7", "Mouth"]
#Print the last term
print(lists[-1]) #print Mouth
#Print the 2nd to the last term
print(lists[-2]) #print 7
Slicing and updating a list
A particular range of items in a list can be gotten from a list using the index number and colon(:).
A list can likewise be updated using the index number.
#Slicing a list
lists = ["boy", "girl", "Deborah", 15, 19, 1.3]
#print the first three items
print(lists[0:3])
#print the last three items
print(lists[3:])
#Updating a list
lists = ["joy", 5, True, 7.5]
#Update the list
lists[2] = "Brave"
#Print the updated list
print(lists)