What is a Python List?
In Python, a list is a collection of items or elements that can be of different types, such as numbers, strings, or other objects. A list is a mutable object, meaning that its contents can be modified after it is created. Lists in Python are similar to arrays in other programming languages, but they are more flexible and have more built-in functions.
Creating a Python List
To create a list in Python, we can use square brackets and separate the items with commas. Here is an example of how to create a list:
my_list = [1, 2, 3, "four", 5.6]
In this example, the list contains integers, a string, and a float.
Note that a list can contain items of different types.
Accessing Elements in a Python List
We can access individual elements in a list by using their index, which starts at 0. Here is an example:
my_list = [1, 2, 3, "four", 5.6]
print(my_list[0])
# Output: 1
print(my_list[3])
# Output: four
In this example, we use the index to access the first and fourth elements of the list.
Modifying Elements in a Python List
We can modify elements in a list by assigning new values to their indexes.
Here is an example:
my_list = [1, 2, 3, "four", 5.6]
my_list[2] = "three"
print(my_list)
# Output: [1, 2, 'three', 'four', 5.6]
In this example, we use the index to modify the third element of the list and replace it with a string.
Adding Elements to a Python List
We can add elements to a list by using the append()
method.
Here is an example:
my_list = [1, 2, 3]
my_list.append(4)
print(my_list)
# Output: [1, 2, 3, 4]
In this example, we use the append()
method to add the integer 4 to the end of the list.
Looping Through a Python List
We can loop through a list using a for
loop.
Here is an example:
my_list = [1, 2, 3, 4, 5]
for item in my_list:
print(item)
In this example, we use a for
loop to print each item in the list on a new line.
Conclusion
In summary, a list is a fundamental data structure in Python that is used extensively in many Python programs. Lists can contain elements of different types, and we can modify them, add elements to them, and loop through them. With these basic operations, we can build more complex programs that utilise lists to store and manipulate data.
Nice Post for Beginners..
ReplyDelete