Working with list in python


Working with list in python

List is a one of the most used data types in python programming.  It is a heterogeneous and  ordered set of data structure in python. As it is an ordered data structure so, it obiviously supports indexing. We can access the elements of a list using index. It supports both positive and negative indexing. Positive index starts from 0 and negative index starts from -1. In general we call negative indexing as reverse indexing.

Basic operations of List in Python

  • Representation of list
    # create an empty list
    lst = []
    # create a list with initial elements
    lst = [1,2,3]
    # type conversion using "list" built-in function
    s = 'google'
    ouput = list(s)
    print(ouput)
    # Output: ['g', 'o', 'o', 'g', 'l', 'e']
    d ={1:1, 2:2}
    ouput = list(d)
    print(ouput)
    # Output: [1,2]
    t = (1, 2, 'a')
    ouput = list(t)
    print(ouput)
    # Output: [1,2]
    
  • Accessing element in a list using indexes
    lst = ["hi", "hello", 3.27, 1000, {1:1}]
    d = lst[-1]
    print(d)
    # Output: {1:1}
    s = lst[0]
    print(s)
    # Output: hello
    not_exists = lst[100]
    # Output: IndexError: list index out of range
    
    We can store objects any kinds in the list data structure in python. In above code we have accessed the elements with both positive and negative indexes. When we access with index that is not in the range of objects we get IndexError.

Working with list methods in python

  • Working with "append" list method in python
    # L.append(object) -- append object to end
    lst = ["hi", "hello"]
    new_obj = "world"
    lst.append(new_obj)
    print(lst)
    # Output: ["hi", "hello", "world"]
    When append an object to the list it inserted at end or right after the last object in the list.
  • Working with "count" list method in python
    # L.count(value) -> integer -- return number of occurrences of value
    lst = ['hi', 'hello', 'world', 'hi']
    count = lst.count('hi')
    print(count)
    # Output: 2
    Using this method we can count the number of occurences of a given object.
  • Working with "extend" list method in python
    # L.extend(iterable) -- extend list by appending elements from the iterable
    lst = ['hi', 'hello', 'world']
    iter_obj = (1,2,3,4)
    lst.extend(iter_obj)
    print(lst)
    # Output: ['hi', 'hello', 'world', 1, 2, 3, 4]
    
    Using this method we can add the group of objects to the list in a single operation.
  • Working with "index" list method in python
    # L.index(value, [start, [stop]]) -> integer -- return first index of value.
    lst = ['hi', 'hello', 'world']
    index = lst.index("world")
    print(index)
    # Output: 2
    
    It returns the positive index of firrst occurence of the given object/element. Raises ValueError if the value is not present. We can specify the start and end indexes to look for given object.
  • Working with "insert" list method in python
    # L.insert(index, object) -- insert object before index
    lst = ['hi', 'hello', 'world']
    lst.insert(1, "google")
    print(lst)
    # Output: ['hi', 'google', 'hello', 'world']
    
    "insert" method inserts an object in a given index. It will not replace the object of a given index.
  • Working with "pop" list method in python
    # L.pop([index]) -> item -- remove and return item at index (default last).
    lst = ['hi', 'hello', 'world']
    pop_obj = lst.pop(1)
    print(pop_obj)
    # Output: 'hello'
    pop_obj = lst.pop(100)
    print(pop_obj)
    # Output: IndexError
    
    It removes the object at a given index and returns the object.It raises IndexError if list is empty or index is out of range.
  • Working with "remove" list method in python
    # L.remove(value) -> None
    lst = ['hi', 'hello', 'world', 'hello']
    lst.remove('hello')
    print(lst)
    # Output: ['hi', 'world', 'hello']
    lst.remove('hyd')
    # Output: ValueError: list.remove(x): x not in list
    
    Remove first occurrence of value and Raises ValueError if the value is not present.
  • Working with "reverse" list method in python
    # L.reverse() --> None
    lst = ['world', 'hello', 0, 3, 'hello', 'hi', 4, 2, 1]
    lst.reverse()
    print(lst)
    # Output: [1, 2, 4, 'hi', 'hello', 3, 0, 'hello', 'world']
    
    It reverses the list (INPLACE).  It will permanently reverses the list. If you don't want permanently then use "reversed" builtin function.
  • Working with "sort" list method in python
    # L.sort(cmp=None, key=None, reverse=False)  --> None
    lst = [0, 4, 2, 1]
    lst.sort()
    print(lst)
    # Output: [0, 1, 2, 4]
    
    Use if only if you have same kind of data objects otherwise it will throw "TypeError".

References:
https://developers.google.com/edu/python/lists

https://docs.python.org/3/tutorial/datastructures.html

Read Next: working with vim editor in ubuntu

Read Prev: Working with frozenset data type in python

Blog Archive