Friday, July 1, 2022

Python - Add or remove items from a list

# Add an item to a list
myList = ["apple", "banana", "cherry"]
myList.append("orange")
print(myList)

# Add multiple items to a list
myList = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
myList.extend(tropical)
# ['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']
print(myList)

# Insert an item mid-list
myList = ["apple", "banana", "cherry"]
myList.insert(1,"orange")
# ['apple', 'orange', 'banana', 'cherry']
print(myList)

# Remove an item from a list
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
# ['apple', 'cherry']
print(thislist)

# Pop method to remove the list item from a list
thislist = ["apple", "banana", "cherry"]
thislist.pop()
# ['apple', 'banana']
print(thislist)

# Pop method with an index value targets that item in list
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
# ['apple', 'cherry']
print(thislist)

# Delete method
thislist = ["apple", "banana", "cherry"]
del thislist[0]
# ['banana', 'cherry']
print(thislist)

# Delete the entire list
thislist = ["apple", "banana", "cherry"]
del thislist
# This will generate an error because the list itself is deleted,
#  not simply emptied of all items.
#print(thislist)

# This is the way to empty all items from a list
thislist = ["apple", "banana", "cherry"]
thislist.clear()
# []
print(thislist)