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.
my_list = [1, 2, 3, 4, 5]
print(my_list[1:3])
List slicing [1:3] returns elements from index 1 (inclusive) to index 3 (exclusive), which are elements at positions 1 and 2.
pop() removes and returns the last element (or element at specified index). remove() only removes value, doesn't return it.
Square brackets [] create a list object. Lists in Python can contain elements of different data types (heterogeneous).
In Python, the string data type is represented as 'str', not 'string'. 'string' is not a built-in data type.
my_list = [1, 2, 3]
my_list.append(4)
print(len(my_list))
append() adds one element to the list. Initial length is 3, after append(4) it becomes 4.
python
x = [1, 2, 3]
y = x
y.append(4)
print(x)
What will be the output?
In Python, when you assign y = x, both variables reference the same list object in memory. When you modify the list using y.append(4), the original list x is also modified because they point to the same object. Therefore, print(x) outputs [1, 2, 3, 4].