Junior
What are the methods of working with lists in Python?
sobes.tech AI
Answer from AI
# creating a list
my_list = [1, 2, 3, 4, 5]
Methods for modifying a list in place:
append(item): Adds an element to the end of the list.extend(iterable): Extends the list by adding elements from an iterable.insert(index, item): Inserts an element at the specified index.remove(item): Removes the first occurrence of the specified element. RaisesValueErrorif the element is not found.pop([index]): Removes and returns the element at the specified index. If no index is specified, removes and returns the last element.clear(): Removes all elements from the list.sort(key=None, reverse=False): Sorts the elements of the list. Defaults to ascending order.reverse(): Reverses the order of the list.
Methods for retrieving information about a list:
count(item): Returns the number of occurrences of the specified element.index(item, start=0, end=len(list)): Returns the index of the first occurrence of the specified element. RaisesValueErrorif the element is not found. You can specify start and end indices for the search.
# Examples of using methods
my_list.append(6) # [1, 2, 3, 4, 5, 6]
my_list.extend([7, 8]) # [1, 2, 3, 4, 5, 6, 7, 8]
my_list.insert(0, 0) # [0, 1, 2, 3, 4, 5, 6, 7, 8]
my_list.remove(3) # [0, 1, 2, 4, 5, 6, 7, 8]
popped_item = my_list.pop(1) # popped_item = 1, my_list = [0, 2, 4, 5, 6, 7, 8]
my_list.sort() # [0, 2, 4, 5, 6, 7, 8]
my_list.reverse() # [8, 7, 6, 5, 4, 2, 0]
item_count = my_list.count(5) # item_count = 1
item_index = my_list.index(4) # item_index = 4
my_list.clear() # []