my_list = [3, 1, 4, 1, 5]
my_list.sort()
print(my_list)
sort() arranges list elements in ascending order by default. It modifies the list in-place.
my_list = [[1, 2], [3, 4], [5, 6]]
print(my_list[1][0])
my_list[1] returns [3, 4], and [3, 4][0] returns 3 (first element of the nested list).
my_list = [1, 2, 2, 3, 2, 4]
print(my_list.count(2))
count() returns the number of occurrences of a value. The value 2 appears 3 times in the list.
my_list = [1, 2, 3]
my_list.extend([4, 5])
print(my_list)
extend() unpacks the iterable and adds individual elements. append() would add the list as a single element.
Lists (created with []) can be modified after creation, while tuples (created with ()) cannot be changed after initialization.
my_list = [1, 2, 3]
result = 2 in my_list
The 'in' operator checks membership. Since 2 exists in my_list, the expression evaluates to True.
my_list = [10, 20, 30]
my_list[1] = 25
print(my_list)
Lists are mutable. Assignment my_list[1] = 25 changes the element at index 1 from 20 to 25.
range(1, 6) generates 1 to 5 (exclusive end), and explicit list [1,2,3,4,5] both work. Both statements are correct.
len() counts the number of top-level elements in the list: 1, [2,3], 4, and [5,[6,7]] = 4 elements total.