Python

Python List Methods

Hello in this tutorial, we will see how to implement different list methods in python programming.

1. Introduction

The list data structure in python programming is:

  • A data structure that can store multiple data at once (in other words it is a comma separate items between the square brackets and the items can be of the different or same type)
  • It is an ordered collection
  • Each element in a list have a distinct place in the sequence and will not eradicate the duplicates
  • It is mutable in nature (i.e. we can add and remove the entries

The useful list methods in python programming are –

  • insert(…): Used to insert an item to the list at a given position. Represented by the syntax as – insert(position, list)
  • append(…): Used to insert an item at the end of the list. Represented by the syntax as – append(list)
  • remove(…): Remove an element from the list. If the element exists it will be removed from the list otherwise ValueError will be thrown. Represented by the syntax as – remove(item_to_be_removed)
  • extend(…): Used to merge two lists and store the results in the first list. Represented by the syntax as – first_list.extend(second_list)
  • count(…): Used to count the number of times the given element appears in the list. Represented by the syntax as – list.count(search_key)
  • index(…): Used to find the position of the given element in the list. If the element exists return the position value of the element in the list otherwise ValueError is thrown. Represented by the syntax as – list.index(search_key)
  • copy(…): Used to make a copy of the original list. Represented by the syntax as – original_list.copy()
  • sort(…): Used to sort the data of the list in ascending order. Represented by the syntax as – list.sort()
  • reverse(): Used to reverse the items in the list. Represented by the syntax as – list.reverse()
  • clear(): Used to remove all items from the list. Represented by the syntax as – list.clear()
  • pop(): Used to remove an element from the given index
    • If no index value is passed the default index -1 is passed to remove the last item from the list
    • If an invalid index value is passed IndexError will be thrown
    • The method returns the item present at the given index
    • Represented by the syntax as – list.pop(index_value)

1.2 Setting up Python

If someone needs to go through the Python installation on Windows, please watch this link. You can download the Python from this link.

2. Python List Methods

Let us dive in with the programming stuff now. I am using JetBrains PyCharm as my preferred IDE. You’re free to choose the IDE of your choice.

2.1 Creating an implementation file

Let us understand the implementation with the help of a python script.

Implementation file

# useful methods under python list

# insert element in list at a given position
def insert_item_to_list(items, item, position):
    items.insert(position, item)
    print('List after insert = {}'.format(items))


# insert element at the end of the list
def append_item_to_list(items, item):
    items.append(item)
    print('List after append = {}'.format(items))


# remove element from the list
def remove_item_from_list(items, item_to_be_removed):
    try:
        print('Item to be removed = {}'.format(item_to_be_removed))
        items.remove(item_to_be_removed)
        print('List after remove = {}'.format(items))
    except ValueError:
        print('Item does not exist')


# merge two lists into one and store the merged items in first list
def merge_lists(list1, list2):
    list1.extend(list2)
    print('Updated list = {}'.format(list1))


# count the number of times a given item appears in the list
def count_element(items, search_key):
    count = items.count(search_key)
    print('{} appear {} times'.format(search_key, count))


# obtain the position of the item in the list
def find_item_pos(items, search_key):
    try:
        pos = items.index(search_key)
        print('{} found at position = {}'.format(search_key, (pos + 1)))
    except ValueError:
        print('Item does not exist')


# make a copy of the original list
def copy_list(items):
    copied_list = items.copy()
    print('Copied list = {}'.format(copied_list))


# sort the list in ascending order
def sorted_list(items):
    items.sort()
    print('Sorted list = {}'.format(items))


# reverse the items in the list
def reversed_list(items):
    items.reverse()
    print('Reversed list = {}'.format(items))


# remove all items from the list and return an empty list
def clear_list(items):
    items.clear()
    print('List cleared')


# remove the item from the list at a given index
def pop_item_from_list(items, index):
    popped_item = items.pop(index)
    print('Removed item = {}'.format(popped_item))
    print('Updated list = {}'.format(items))


# driver code
if __name__ == '__main__':
    phones = ['Apple', 'Android', 'Blackberry', 'Windows', 'Galaxy', 'HTC', 'LG']
    print('Original list = {}\n'.format(phones))

    # uncomment the method to check its working. have fun
    # insert_item_to_list(phones, 'Samsung', 3)
    # append_item_to_list(phones, 'Xperia')
    # remove_item_from_list(phones, 'LG')
    # merge_lists(phones, ['Wiko', 'Nokia'])
    # count_element(phones, 'Apple')
    # find_item_pos(phones, 'HTC')
    # copy_list(phones)
    # sorted_list(phones)
    # reversed_list(phones)
    # pop_item_from_list(phones, 2)
    # clear_list(phones)

You can uncomment the method of your choice and run this python script. For the demo, I have uncommented all the methods and if everything goes well the output will be shown in the IDE console.

Console output

Original list = ['Apple', 'Android', 'Blackberry', 'Windows', 'Galaxy', 'HTC', 'LG']

List after insert = ['Apple', 'Android', 'Blackberry', 'Samsung', 'Windows', 'Galaxy', 'HTC', 'LG']
List after append = ['Apple', 'Android', 'Blackberry', 'Samsung', 'Windows', 'Galaxy', 'HTC', 'LG', 'Xperia']
Item to be removed = LG
List after remove = ['Apple', 'Android', 'Blackberry', 'Samsung', 'Windows', 'Galaxy', 'HTC', 'Xperia']
Updated list = ['Apple', 'Android', 'Blackberry', 'Samsung', 'Windows', 'Galaxy', 'HTC', 'Xperia', 'Wiko', 'Nokia']
Apple appear 1 times
HTC found at position = 7
Copied list = ['Apple', 'Android', 'Blackberry', 'Samsung', 'Windows', 'Galaxy', 'HTC', 'Xperia', 'Wiko', 'Nokia']
Sorted list = ['Android', 'Apple', 'Blackberry', 'Galaxy', 'HTC', 'Nokia', 'Samsung', 'Wiko', 'Windows', 'Xperia']
Reversed list = ['Xperia', 'Windows', 'Wiko', 'Samsung', 'Nokia', 'HTC', 'Galaxy', 'Blackberry', 'Apple', 'Android']
Removed item = Wiko
Updated list = ['Xperia', 'Windows', 'Samsung', 'Nokia', 'HTC', 'Galaxy', 'Blackberry', 'Apple', 'Android']
List cleared

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

3. Summary

In this tutorial, we learned:

  • Different list methods in the python programming
  • Sample programming stuff

You can download the source code of this tutorial from the Downloads section.

4. Download the Project

This was a tutorial to explore the different list methods in python programming.

Download
You can download the full source code of this example here: Python List Methods

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button