In computing, a list is a fundamental data structure used to store multiple data items that can be accessed by indices. In Python programming, a list is created by placing items (which could be integers, float, strings, etc) inside a square bracket [ ], separated by a comma. We are going to show you how simple and versatile Python lists are, and how to define them.
Step 1: Understanding Python List
A list is an in-built data type in Python. It is used to store multiple items in a single variable. Lists are created by placing all the items (elements) inside a square bracket [ ], separated by commas. It can have any number of items and they may be of different types (integer, float, string, etc.).
Step 2: How to Define a List
To define a list in Python, you use square brackets. Inside these brackets, you can place elements separated by commas. This is how to create a simple Python list:
1 |
fruits = ['apple', 'banana', 'cherry', 'dates'] |
In this case, “fruits” is the name of your list, and ‘apple’, ‘banana’, ‘cherry’, and ‘dates’ are the elements within the list.
Step 3: Accessing List Items
In Python, the items in a list are list are ordered, changeable, allow duplicate values and indexed. The first index is [0], the second index is [1], and so forth. Hence, to reference or pull a value from a list, you can use its index. For example:
1 |
print(fruits[0]) |
This will output:
apple
Step 4: Changing List Items
To change a value in a Python list, reference the list name followed by the index of the value you want to change, and then provide the new value. Here’s how you do it:
1 |
fruits[1] = 'blueberry' |
Then printing the list:
1 |
print(fruits) |
will output:
['apple', 'blueberry', 'cherry', 'dates']
Displaying the Full Code
1 2 3 4 5 6 7 8 9 10 11 |
# Defining the list fruits = ['apple', 'banana', 'cherry', 'dates'] # Accessing list items print(fruits[0]) # Changing list items fruits[1] = 'blueberry' # Printing the changed list print(fruits) |
Conclusion
Learning how to define a list in Python not only provides you with a versatile tool, but it’s also the first step in an exciting journey towards becoming proficient in Python data structures.