How To Use Python List Example

Python list is a sequence of object which is similar with other programming language’s array. 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.

>>> coding_list = ['python', 'java']
>>> coding_list
['python', 'java']

# get list item by index
>>> coding_list[1]
'java'

2. Insert Object Into Python List.

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.

>>> coding_list.append(888)
>>> coding_list
['python', 'Html', 'java', 888]

4. Get First Three List Elements.

Please note the slice operation 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.

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.

Python list remove method can remove a specifed 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.

Python list 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.

<Python List> * n will create a new python list object with n times original list items. Please not this action do 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.

The extend method will merge target list items into current one.

>>> coding_list.extend(['jquery','android'])
>>> coding_list
['python', 'java', 'jquery', 'android']

>>> coding_list[2]
'jquery'

If you use 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.

Python list 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 error TypeError: ‘<‘ not supported between instances of ‘list’ and ‘str’.

>>> 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'

Below is 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.

Sometimes you want to return another sorted list object based on the original list copy, you can use Python built-in sorted() or reversed() method. These two method will return a copy of the original list and sort the list items in either ascending or descending order.

  1. 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']
    
  2. 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.

List comprehension is used to generate a python list data by a for loop statement. The list data will be created at once. But if there are so many 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.

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 larget data set. Python use ( ) not [ ] to create list generator expresson.

# 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(_)
READ :   What Does Double Underscore ( __ ) Means In Django Model QuerySet Objects Filter Method

Leave a Reply

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.