Lists are probably the most versatile data structures in Python. A list can be defined by writing a list of comma separated values in square brackets. Lists might contain items of different types. Python lists are mutable – individual elements of a list can be changed while the identity does not change.
Country =['NEPAL','INDIA','USA','GERMANY','UK','AUSTRALIA'] Temperature =[22, 44, 28, 20, 18, 25, 45, 67]
We just created two lists, one for Country names (strings) and another one for Temperature data (whole numbers).
Accessing individual elements of a list
- Individual elements of a list can be accessed by writing an index number in square bracket. The first index of a list starts with 0 (zero) not 1. For example, Country can be used to access the first element, ‘INDIA’
- A range of elements can be accessed by using start index and end index but it does not return the value of the end index. For example, Temperature[1:4] returns three elements, the second through fourth elements [28, 20, 18], but not the fifth element
# Create a list of squared numbers
squares_list = [0, 1, 4, 9, 16, 25]
# Now write a line of code to create a list of the first five odd numbers and store it in a variable odd_numbers
odd_numbers= [1, 3, 5, 7, 9]
# Print the first element of squares_list
# Print the second to fourth elements of squares_list
Practice it in DataCamp here