Python List

In Python, a list is a collection of values that can be of different data types, such as integers, strings, or even other lists. Lists are mutable, meaning that you can modify them by adding, removing, or changing elements.

Here's an example of how to create a list in Python:

‮efer‬r to:theitroad.com
my_list = [1, 2, 3, "four", 5.0]

In this example, we've created a list with five elements: the integers 1, 2, and 3, the string "four", and the floating-point number 5.0.

You can access elements of a list by their index, which starts at 0 for the first element:

print(my_list[0])    # prints 1
print(my_list[3])    # prints "four"

You can also use negative indexing to access elements from the end of the list:

print(my_list[-1])   # prints 5.0
print(my_list[-2])   # prints "four"

You can add elements to a list using the append() method:

my_list.append("six")

This adds the string "six" to the end of the list.

You can remove elements from a list using the remove() method:

my_list.remove(2)

This removes the element with the value 2 from the list.

You can modify elements of a list by assigning a new value to them:

my_list[0] = 0

This changes the first element of the list from 1 to 0.

You can also use list slicing to create a new list from a subset of the original list:

new_list = my_list[1:4]

This creates a new list containing the second, third, and fourth elements of the original list.

These are just a few examples of the many ways that you can work with lists in Python. Lists are a powerful and flexible data type that can be used in a wide range of applications.