In Python, lists are a commonly used data structure that allow you to store and manipulate collections of data. A list is a mutable ordered collection of elements, which can be of any data type.
Here is an example of creating and working with a list in Python:
python # Create a list my_list = [1, 2, 3, "four", 5.0] # Access elements of the list print(my_list[0]) # Output: 1 print(my_list[3]) # Output: "four" # Add an element to the list my_list.append(6) # Remove an element from the list my_list.remove("four") # Iterate over the elements of the list for item in my_list: print(item)
In this example, a list called `my_list` is created with five elements of different data types. The `print()` function is used to access and output the first and fourth elements of the list. The `append()` method is used to add an element to the end of the list, and the `remove()` method is used to remove the element `”four”` from the list. Finally, a `for` loop is used to iterate over the elements of the list and output them to the console.
Lists in Python can also be sliced, meaning that you can extract a portion of the list. Here is an example:
python # Create a list my_list = [1, 2, 3, 4, 5] # Slice the list slice1 = my_list[1:3] # Output: [2, 3] slice2 = my_list[3:] # Output: [4, 5] slice3 = my_list[:2] # Output: [1, 2]
In this example, the `my_list` list is sliced into three different parts using the slice notation. The first slice (`slice1`) extracts the elements at index 1 and 2, the second slice (`slice2`) extracts the elements from index 3 to the end of the list, and the third slice (`slice3`) extracts the first two elements of the list.
Lists are a versatile data structure in Python and are used extensively in a wide variety of programs.