How To Use Python List Example

Python list is a sequence of objects which is similar to other programming languages’ arrays. Python list object is mutable, resizable and it can hold any data type object. This example will tell you how to create a python list object and how to operate on it to implement add, append, extend, remove, change, get and slice operations.

1. Create Python List.

  1. Run the below source code can create a python list object.
    >>> coding_list = ['python', 'java']
    >>> coding_list
    ['python', 'java']
    
    # get list item by index
    >>> coding_list[1]
    'java'

2. Insert Object Into Python List.

  1. The list object insert method’s first parameter is the inserted index, the second parameter is the inserted object value.
    >>> coding_list.insert(1,'Html')
    >>> coding_list
    ['python', 'Html', 'java']

3. Append Object To Python List.

  1. Use the list object’s append method to append a value object to the end of the list object.
    >>> coding_list.append(888)
    >>> coding_list
    ['python', 'Html', 'java', 888]
    

4. Get The First Three List Elements.

  1. Please note the slice operation ( list_object.[start_index_number : end_index_number] ) will return a new list object. The original list object is not changed.
    >>> coding_list[:3]
    ['python', 'Html', 'java']
    
    # please the original list is not changed.
    >>> coding_list
    ['python', 'Html', 'java', 888]
    >>> 
    >>> 
    >>> tmp_list = coding_list[:3]
    >>> tmp_list
    ['python', 'Html', 'java']
    
    >>> tmp_list.insert(2, 'C++')
    >>> tmp_list
    ['python', 'Html', 'C++', 'java']
    

5. Check Whether The Given Object Exist In Python List Or Not.

  1. The in or not in operator will return a boolean value.
    >>> 'JavaScript' in coding_list
    False
    >>> 
    
    >>> 888 in coding_list
    True
    
    >>> 888 not in coding_list
    False

6. Remove List Item By Item Value Explicitly.

  1. Python list remove method can remove a specified item. The remove method parameter is the list item value.
    >>> coding_list.remove(888)
    >>> coding_list
    ['python', 'Html', 'java']
    

7. Remove List Item By Item Index.

  1. The Python list object’s pop method is used to remove the specified index list item. The pop method parameter is the list item index.
    >>> coding_list.pop(1)
    'Html'
    >>> coding_list
    ['python', 'java']
    

8. Duplicate ( or Multiple Times ) Python List Item To A New List.

  1. <Python List> * n will create a new python list object with n times original list items. Please note this action does not change the original python list, it will create a new python list.
    >>> coding_list * 2
    ['python', 'java', 'python', 'java']
    >>> coding_list
    ['python', 'java']
    

9. Merge Other List Values.

  1. The Python list object’s extend method will merge target list items into the current one.
    >>> coding_list.extend(['jquery','android'])
    >>> coding_list
    ['python', 'java', 'jquery', 'android']
    
    >>> coding_list[2]
    'jquery'
  2. If you use the append method to append another python list object, it will append the target list object as one object in the original list.
    >>> coding_list
    ['python', 'java']
    
    >>> coding_list.append(['jquery','android'])
    >>> coding_list
    ['python', 'java', ['jquery', 'android']]
    
    >>> coding_list[2]
    ['jquery', 'android']
    

10. Sort Python List Items.

  1. The Python list object’s sort method is used to sort the list items, the sort action will be performed on the original list object. But the list items can not be another list object. Otherwise, it will throw the error TypeError: ‘<‘ not supported between instances of ‘list’ and ‘str’.
  2. For example, if one of the original list object’s elements is another list object, when you call it’s sort() method, it will throw the below error.
    >>> coding_list
    ['python', 'java', ['jquery', 'android']]
    
    >>> coding_list.sort()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: '<' not supported between instances of 'list' and 'str'
  3. Below is the python list sort method’s correct usage.
    >>> coding_list
    ['python', 'java', 'jquery', 'android']
    
    >>> coding_list.sort()
    >>> coding_list
    ['android', 'java', 'jquery', 'python']

11. Get A Sorted List Based On The Original List Copy.

  1. Sometimes you want to return another sorted list object based on the original list object’s copy, you can use Python built-in sorted() or reversed() method.
  2. These two methods will return a copy of the original list and sort the list items in either ascending or descending order.
  3. Python reversed() function example.
    >>> coding_list_reversed = reversed(coding_list)
    >>> coding_list_reversed
    <list_reverseiterator object at 0x7fae84839b70>
    >>> for _ in coding_list_reversed:
    ...     print(_)
    ... 
    python
    jquery
    java
    android
    >>> coding_list
    ['android', 'java', 'jquery', 'python']
    
  4. Python sorted() function example.
    >>> coding_list = ['java','python','c++','javascript','jquery','android']
    
    >>> coding_list_sorted = sorted(coding_list)
    >>> coding_list_sorted
    ['android', 'c++', 'java', 'javascript', 'jquery', 'python']
    >>> 
    >>> coding_list
    ['java', 'python', 'c++', 'javascript', 'jquery', 'android']
    

12. List Comprehension.

  1. List comprehension is used to generate python list data by a for loop statement. The list data will be created at once. But if there are so much data in the list, you had better use list generator expression.
    >>> list = [x**2 for x in range(10)]
    >>> list
    [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
    

13. List Generator Expression.

  1. List generator expression has a character of lazy evaluation, it will not create all the list data at once, it will create one list item at one time when you need it. This is very useful for large data sets. Python use ( ) not [ ] to create a list generator expression.
    # create list generator expression.
    >>> list = (x**2 for x in range(10000000))
    
    # output the generator object.
    >>> list
    <generator object <genexpr> at 0x7fae8496bc00>
    
    # use for loop to iterate the list item, only can show list item in this way.
    >>> for _ in list:
    ...     print(_)

14. Get The List Elements’ Number.

  1. You can use the len() function to get the number of elements in the Python list object, below is an example.
    >>> coding_list = ['python', 'java', 'javascript']
    >>> 
    >>> len(coding_list)
    3
    >>>
  2. Python uses the __len__() function to implement the len() function internally, so you can use the python object’s __len__() method to get the list object’s size.
    >>> coding_list.__len__()
    3
  3. From the below source code, we can see all the python classes in the list have the built-in __len__ method. But not all the python classes in the list have the method len().
    >>> all(hasattr(cls, '__len__') for cls in (str, bytes, tuple, list, 
    ...                                             range, dict, set, frozenset))
    True
    >>> 
    >>> all(hasattr(cls, 'len') for cls in (str, bytes, tuple, list,
    ...                                             range, dict, set, frozenset))
    False
  4. You can create a custom python class and define a length property to it, then you can get the number of the python list elements by calling the list object’s length property. Below is the example code.
    >>> class coding_list(list): # define a custom python class.
    ...     @property            # define a length property.
    ...     def length(self):
    ...         return len(self)
    ... 
    >>> c_list = coding_list(['python', 'java', 'c++']) # create the python object of the custom python class.
    >>> 
    >>> c_list.length # call it's length property.
    3
    >>> print(c_list)
    ['python', 'java', 'c++']
  5. The operator.length_hint is another option besides the len() function. Before you can use it, you should add the code from operator import length_hint in your python source code to import it. The length_hint() method can also get the list iterator object’s length also besides the list object element’s size.
    >>> from operator import length_hint  # import the length_hint class from the operator package.
    >>> 
    >>> coding_list = ['python','java','c++']
    >>> 
    >>> print(len(coding_list)) # get the list object's length by the len() function.
    3
    >>> 
    >>> print(length_hint(coding_list)) # get the list object's length by the length_hint() function.
    3
    >>> 
    >>> iter_obj = iter(coding_list) # get the list object's iterator object.
    >>> 
    >>> print(length_hint(iter_obj)) # get the iterator object's size with the length_hint() function.
    3
    >>> len(iter_obj) # can not get the iterator object's size with the len() function.
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: object of type 'list_iterator' has no len()
  6. The python len() and length_hint() function is more safer than the __len__() function because they do some security checks, but __len__() is only defined for the python built-in classes such as a list.
  7. But the length_hint() function will return hints only as of the function name meanings, so the len() method is the most recommended function to use in your python source code.

Leave a Comment

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

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

Clicky