Python List Operations and Features

In Python, a list is a sequence type similar to tuples, but unlike tuples, lists are mutable, meaning their contents can be modified. Lists are created using square brackets with elements separated by commas. For example, the following code defines a list containing three elements:

my_list = [1, "hello", 3.14]

Each element in the list can be accessed via its index position within the list. To access the first element, use the following syntax:

my_list[0]

Lists support many common sequence operations, such as slicing, concatenation, and repetition. For example, to retrieve the first two elements of a list, use the following syntax:

my_list[:2]

You can also concatenate two lists using the plus operator, for example:

my_list + [4, 5, 6]

Unlike tuples, lists are mutable; that is, you can add, remove, and modify elements within a list. For example, to append an element to the end of a list, use the append() method:

my_list.append(42)

To remove an element from a list, use the remove() method:

my_list.remove("hello")

To modify an element within a list, you can assign a new value directly via indexing:

my_list[0] = 100

It is important to note that, unlike tuples, lists are mutable. Consequently, unexpected side effects may occur in certain scenarios. For example, if multiple variables reference the same list and one variable modifies it, all other variables referencing that list will also observe the modification.