Answers for "list methods"

80

list methods python

list.append(x) # append x to end of list
list.extend(iterable) # append all elements of iterable to list
list.insert(i, x) # insert x at index i
list.remove(x) # remove first occurance of x from list
list.pop([i]) # pop element at index i (defaults to end of list)
list.clear() # delete all elements from the list
list.index(x[, start[, end]]) # return index of element x
list.count(x) # return number of occurances of x in list
list.reverse() # reverse elements of list in-place (no return)
list.sort(key=None, reverse=False) # sort list in-place
list.copy() # return a shallow copy of the list
Posted by: Guest on March-03-2020
2

list functions

list.append()
list.clear()
list.copy()	
list.count()
list.extend()
list.index()     
list.insert()	
list.pop()	
list.remove()	
list.reverse()	
list.append()	
list.clear()	
list.copy()	
list.count()	
list.extend()	
list.index()	
list.insert()	
list.pop()	
list.remove()	
list.reverse()	
list.sort()	
sorted(list)
Posted by: Guest on June-05-2021
1

list methods

my_list = ["banana", "cherry", "apple"]

# len() : get the number of elements in a list
print("Length:", len(my_list))

# append() : adds an element to the end of the list
my_list.append("orange")

# insert() : adds an element at the specified position
my_list.insert(1, "blueberry")
print(my_list)

# pop() : removes and returns the item at the given position, default is the last item
item = my_list.pop()
print("Popped item: ", item)

# remove() : removes an item from the list
my_list.remove("cherry") # Value error if not in the list
print(my_list)

# clear() : removes all items from the list
my_list.clear()
print(my_list)

# reverse() : reverse the items
my_list = ["banana", "cherry", "apple"]
my_list.reverse()
print('Reversed: ', my_list)

# sort() : sort items in ascending order
my_list.sort()
print('Sorted: ', my_list)

# use sorted() to get a new list, and leave the original unaffected.
# sorted() works on any iterable type, not just lists
my_list = ["banana", "cherry", "apple"]
new_list = sorted(my_list)

# create list with repeated elements
list_with_zeros = [0] * 5
print(list_with_zeros)

# concatenation
list_concat = list_with_zeros + my_list
print(list_concat)

# convert string to list
string_to_list = list('Hello')
print(string_to_list)
Posted by: Guest on August-01-2021

Python Answers by Framework

Browse Popular Code Answers by Language