How to Create a List in Python

To create a list in Python:

list_name = ['item1', 'item2', 'item3', ....]

Examples

Here are examples of two lists in Python:

(1) List of products – this list contains strings (by placing the values within quotes):

products = ["microwave", "oven", "toaster", "refrigerator", "dishwasher"]

(2) List of prices – this list contains numbers (i.e., integers) without quotes:

prices = [300, 700, 120, 1300, 950]

Here is the full Python code to create the two lists:

products = ["microwave", "oven", "toaster", "refrigerator", "dishwasher"]
prices = [300, 700, 120, 1300, 950]

print(products)
print(prices)

Run the code in Python, and you’ll get the following two lists:

['microwave', 'oven', 'toaster', 'refrigerator', 'dishwasher']
[300, 700, 120, 1300, 950]

You can quickly verify that you created lists using type():

products = ["microwave", "oven", "toaster", "refrigerator", "dishwasher"]
prices = [300, 700, 120, 1300, 950]

print(type(products))
print(type(prices))

You’ll now see that indeed you have two lists:

<class 'list'>
<class 'list'>

How to Access an Item within a list

You can access an item within a list in Python by referring to the item’s index:

list_name[index of the item to be accessed]

Where the index of the first item is zero, and then increases sequentially.

For example, to access the third item (index of 2) in both the ‘products‘ and ‘prices‘ lists:

products = ["microwave", "oven", "toaster", "refrigerator", "dishwasher"]
prices = [300, 700, 120, 1300, 950]

print(products[2])
print(prices[2])

You’ll get the third item in each list:

toaster
120

You can also access a range of values in your lists. For instance, to access the last 3 products in the ‘products‘ list (index range of 2:5):

products = ["microwave", "oven", "toaster", "refrigerator", "dishwasher"]
prices = [300, 700, 120, 1300, 950]

print(products[2:5])

The last 3 products:

['toaster', 'refrigerator', 'dishwasher']

You can even perform arithmetic operations. For example, to deduct the first price (index of 0) from the second price (index of 1):

products = ["microwave", "oven", "toaster", "refrigerator", "dishwasher"]
prices = [300, 700, 120, 1300, 950]

print(prices[1] - prices[0])

So the value that you’ll get is 700-300= 400:

400

Check the following tutorials about lists: