7 list functions every Python programmer should know
7 List Functions Every Python Programmer Should Know
-
len(list)
This function returns the length (number of items) of a list.
my_list = [1, 2, 3, 4, 5] list_length = len(my_list) print(list_length) # Output: 5 -
append(item)
This method adds a new item to the end of a list.
fruits = ["apple", "banana", "cherry"] fruits.append("orange") print(fruits) # Output: ["apple", "banana", "cherry", "orange"] -
extend(iterable)
This method adds all the items from an iterable (like another list or a tuple) to the end of the existing list.
numbers = [1, 2, 3] more_numbers = [4, 5, 6] numbers.extend(more_numbers) print(numbers) # Output: [1, 2, 3, 4, 5, 6] -
index(item)
This method returns the index (position) of the first occurrence of an item in the list. If the item is not found, it raises a
ValueError.colors = ["red", "green", "blue", "green"] first_green_index = colors.index("green") print(first_green_index) # Output: 1 -
sort(reverse=False)
This method sorts the items of a list in place. By default (reverse=False), it sorts in ascending order. You can optionally set reverse=True for descending order.
my_list = [3, 1, 4, 5, 2] my_list.sort() # Sorts the list in place print(my_list) # Output: [1, 2, 3, 4, 5] -
insert(index, item)
This method inserts an item at a specified index in the list.
weekdays = ["Monday", "Wednesday", "Friday"] weekdays.insert(1, "Tuesday") # Insert Tuesday at index 1 print(weekdays) # Output: ["Monday", "Tuesday", "Wednesday", "Friday"] -
remove(item)
This method removes the first occurrence of a specified item from the list. If the item is not found, it raises a
ValueError.vegetables = ["carrot", "potato", "carrot", "broccoli"] vegetables.remove("carrot") # Removes the first carrot print(vegetables) # Output: ["potato", "carrot", "broccoli"]


Comments
Post a Comment