So far, we’ve seen variables representing an individual piece of data like
str. Python provides an ability to work with containers of data, which contain other data types. In Python, lists are widely used in many applications to represent an ordered sequence of elements. For example, to keep track of the days in each month of the year, we can have:
january = 31 february = 28 march = 31 april = 30 may = 31 # ... # ... november = 30 december = 31
month_days = [31, 28, 31, 30, 31, ..., 30, 31]
In the code on the left, we have declared 12 different variables to keep track of the number of days in each month. Each variable represents a single month in a year. Yet, it’s also possible to do that with a list (example on the right). Here, the list starts with an opening bracket
[and has a closing bracket at the end of the list
]. The elements in the list are separated with commas and each one represents a single value - the number of days in that month.
print(january) # 31 print(february) # 28
print(month_days) # 31 print(month_days) # 28
Note that indexing starts from
0(exactly like in strings). We’ll soon see that a lot of operations are very similar to operations done on strings.
Elements in lists are ordinary variables. One can operate with them as they would do with other variables. For example, in case this year is a leap year, we would want to add
1to February. That can be done with
february += 1or
month_days += 1. Those two operations are identical.
Declare a variable called
alphabetthat keeps all the uppercase letters of the English language:
alphabet = ['A', 'B', ..., 'Z']. The input contains a single integer
n. The program should print the
n-th letter in the alphabet. It’s guaranteed that
1 ≤ n ≤ 26.