List usage Instance
A list that shown which represents the age of a group of student
py
[21, 25, 21, 23, 22, 20]By using method of list:
Define a listand usingvariable nameto store it.Adda number 31 at theend of the listAdda new group of student age /new list[29, 33, 30] at theend of the listGetthefirst elementof the list (Expected: 21)Getthelast elementof the list (Expected: 30)- Find the
index / position of the element"31" in a list - Print the list after making changes to list (included: initial list) / print relevant data
Example
list-usage-example.py
py
# Define a list and using variable name to store it.
student_age = [21, 25, 21, 23, 22, 20]
print(student_age)
# Add a number 31 at the end of the list
student_age.append(31)
print(student_age)
# Add a new group of student age / new list [29, 33, 30] at the end of the list
new_student_age_list = [29, 33, 30]
student_age.extend(new_student_age_list)
print(student_age)
# Get the first element of the list (Expected: 21)
print(student_age[0])
# Get the last element of the list (Expected: 30)
print(student_age[-1])
# Find the index / position of the element "31" in a list
print(student_age.index(31))Results:
[21, 25, 21, 23, 22, 20]
[21, 25, 21, 23, 22, 20, 31]
[21, 25, 21, 23, 22, 20, 31, 29, 33, 30]
21
30
6