List
List
Negative indexing can also be used to access elements from the end of the
list, with -1 representing the last element.
print(my_list[-1]) # Output: True
print(my_list[-2]) # Output: 3.14
SLICING LISTS
Subsets of lists can be extracted using slicing.
my_list=[10, "hello", 3.14, True]
new_list = my_list[1:3]
print(new_list) # Output: ['hello', 3.14]
list1 = [1, 2, 3]
list2 = list1 # list2 now refers to the same list as list1
In the example above, list1 and list2 are aliases because they both point to the
same list in memory. When list2 is modified, the change is also observed in list1.
This behavior can be useful in some situations, but it can also lead to
unexpected results if not handled carefully.
To avoid aliasing and create an independent copy of a list, you can use the copy()
method or slicing:
list1 = [1, 2, 3]
list2 = list1.copy() # Create a new list with the same elements
# or
list3 = list1[:] #slicing also creates a new list
list2.append(4)
print(list1) # Output: [1, 2, 3] - list1 is unchanged
print(list2) # Output: [1, 2, 3, 4]
list3.append(5)
print(list1) # Output: [1, 2, 3] - list1 is unchanged
print(list3) # Output: [1, 2, 3, 5]
In this case, list2 and list3 are independent copies of list1, so modifying one will
not affect the others.