How to Add and Remove Elements to a List in Python

In this article we can discuss about How to Add and Remove Elements to a List in Python .

How to Add & Remove Elements to a List in Python

How to Add & Remove Elements to a List in Python

  • append() – appends a single element to the list.
  • extend() – appends elements of an iterable to the list.
  • insert() – inserts a single item at a given position of the list.

All three methods modify the list in place and return None.

Append Items

To add an item to the end of the list, use the append() method

Example

Using the append() method to append an item

thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)

Insert Items

To insert a list item at a specified index, use the insert() method.

The insert() method inserts an item at the specified index

Example

Insert an item as the second position

thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)

Note: As a result of the examples above, the lists will now contain 4 items.

Extend List

To append elements from another list to the current list, use the extend() method.

Example

Add the elements of tropical to thislist

thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)

The elements will be added to the end of the list.

Add Any Iterable

The extend() the method does not have to append lists, you can add any iterable object (tuples, sets, dictionaries, etc.).

Example

Add elements of a tuple to a list

thislist = ["apple", "banana", "cherry"]
thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)

Remove List Items

Remove Specified Item

The remove() method removes the specified item.

Example

Remove “banana”

thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)

Remove Specified Index

The pop() method removes the specified index.

Example

Remove the second item

thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)

If you do not specify the index, the pop() method removes the last item.

Example

Remove the last item

thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)

The del keyword also removes the specified index

Example

Remove the first item

thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)

The del keyword can also delete the list completely.

Example

Delete the entire list

thislist = ["apple", "banana", "cherry"]
del thislist

Clear the List

The clear() method empties the list.

The list still remains, but it has no content.

Clear the list content

thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)

Also Check out Python Change List Items

If you interested in the Entertainment genre please check this also thebiographys.com

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *