Python list examples Introduction
Python list is a very important data structure in python. Each items in a list is indexed. Lists are similar to arrays.
They are written within brackets '' and each elements are separated by commas.
Example of a list
list = [item1, item2, item3] | | | 0 1 2
All items in the list is arranged in an indexed. These list can be accessed with its index number. For example item1, item2, item3 can be accessed with index 0, index 1, index 2 respectively.
Create Sample list
Let's create a sample python list 'fruits' and find out some of its common functions. We will perform this in a python shell. I have used here Linux environment but you can choose any other environment.
Run python shell on your terminal like this.
$ python >>>
>>>fruits = ['apple', 'orange', 'banana', 'grapes']
Access any items in a list with its index number.
>>>print fruits Output: apple
>>>print fruits Output: orange
>>>print fruits Output: banana
>>>print fruits Output: grapes
To access last item in a list.
>>> content = [4, 5, 7, 8, 2] >>> print content[-1] 2
You can delete any python list with del command.
>>> list = [1, 2, 3, 4, 5, 6, 7, 8]
Delete a range of items from the list.
>>> del list[3:6] >>> list [1, 2, 3, 7, 8]
Delete entire item from the list.
>>> del list[:] >>> list 
Delete the complete list.
>>> del list >>> list <type 'list'>
To discover more about python read our Programming language python tutorial.
Looping a list in python
You can loop a list in python with FOR and IN statement. The below examples will illustrate how to use for and in statement in python
>>> content = [4, 5, 7, 8, 2] >>> for item in content: ... print item ... Output: 4 5 7 8 2
To add numbers in a list in python by using FOR and IN.
bucket = [1, 2, 4, 9, 11] n = 0 for i in bucket: n += i print n Output: 27
Using enumerate function in python
With enumerate function you can access index as well as items in python lists. The below example will show it.
>>> content = [4, 5, 7, 8, 2] >>> for index, item in enumerate(content): ... print index, item ... 0 4 1 5 2 7 3 8 4 2
Using range and len to print index of items in python
To print only index of the items in a python list use the combination of range and len operator.
>>> content = [4, 5, 7, 8, 2] >>> for index in range(len(content)): ... print index ... 0 1 2 3 4
Python flatten list
Flattening a list in python is making a simple list out of a complicated list. In python it can be achieved by number of ways. Let's see some examples of how to flatten list in python.
>>> list = [[1,2],[3,4,5],[6,7,8],] >>> reduce(lambda x,y: x+y,list) [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> import operator >>> list = [[1,2],[3,4,5],[6,7,8],] >>> reduce(operator.concat, list) [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list = [[30.0, 1, 2], [53.8], [24.2], [9.5], [6.2], [1.2]] >>> flattenlist = [val for x in list for val in x] >>> flattenlist [30.0, 1, 2, 53.8, 24.2, 9.5, 6.2, 1.2]
>>> list = [[30.0, 1, 2], [53.8], [24.2], [9.5], [6.2], [1.2]] >>> flattenlist =  >>> for x in list: ... for val in x: ... flattenlist.append(val) ... >>> flattenlist [30.0, 1, 2, 53.8, 24.2, 9.5, 6.2, 1.2]
Python length of list operator
Len operator is used to find length of list in python or number of elements in python lists.
>>> list = [2, 3, 6, 1, 5, 8] >>> len(list) 6
or you can use
>>> list.__len__() 6
In python you cannot use list.len() to find length of a list, instead you have to use list.__len__()
>>> list.len() Traceback (most recent call last): File "main.py", line 4, in print list.len() AttributeError: 'list' object has no attribute 'len'
Combining two python lists
You can combine two python lists with '+' operator. Look at the following example.
>>> list1 = [1, 2, 3, 4] >>> list2 = [5, 6, 7, 8] >>> total = list1 + list2 >>> print total [1, 2, 3, 4, 5, 6, 7, 8]
Built in function in python
There are some list methods which you can use when using python list.
The below is an example of a list where we will apply and test the python list built-in functions.
fruits = ['apple', 'orange', 'banana', 'grapes']
Python Append function
Append function is used to append any element in the list at the end.
Python Insert function
To insert element at the given index. Here, at index 2.
Python Extend function
To append more than one element at the end.
Python Index function
To print index of the element.
print fruits.index('grapes') Output: 3
But what if there are more than one grapes in the list.
>>>fruits = ['apple', 'grapes', 'orange', 'banana', 'grapes', 'guava'] >>>print fruits.index("grapes") 1
With index you can assign search parameters 'start' and 'stop'. In the below example '2' is the index from which it must start searching item 'grapes'.
>>>print fruits.index("grapes", 2) 4
Here, '5' is the index where it must stop searching for elements.
>>>print fruits.index("grapes", 2, 5) 4
Python Remove function
To remove element from the list.
Python Sort function
For sorting a list in python you can use either of the function sorted() or sort(). In both the cases sorting a list is possible but with sort() function original list will not be there any more. For example.
With sorted function both old as well as sorted list will be available.
#!/usr/bin/python list = [6, 9 ,2, 5] print sorted([6, 9 ,2, 5]) print list
Output: [2, 5, 6, 9] [6, 9, 2, 5]
With sort function old list will not be there anymore.
#!/usr/bin/python list = [6, 9 ,2, 5] list.sort() print list
Output: [2, 5, 6, 9]
Python Count function
This function returns number of times item appear in the list.
Python Reverse function
As the name suggests reverse function is used to reverse elements in a list in python.
#!/usr/bin/python name = ['Amanda', 'Catherine', 'Luis', 'Kathy'] name.reverse() print name
Output: ['Kathy', 'Luis', 'Catherine', 'Amanda']
Python Pop function
Pop function removes element from the list present at the given index. Index is taken as an argument with pop.
Let's see an example of removing an item from the list at index 2.
city = ['NYC', 'LA', 'CA', 'TX'] city.pop(2) print city
Output: ['NYC', 'LA', 'TX']
Python Slices in list
Slicing in python means picking out a range of items from the list. A new list will be created with those picked up list. The below example will illustrate it.
>>>fruits = ['apple', 'orange', 'banana', 'grapes', 'mango']
Slicing index of the list is like this.
['apple', 'orange', 'banana', 'grapes', 'mango']
| | | | |
0 1 2 3 4
Functional programming tools in python
There are some functional programming tools in python. You can use these built-in function with python list. These functions are.
- filter(function, sequence)
- reduce(function, sequence)
- map(function, sequence)
Lambda function in python
Lambda function is a function without name. They are mainly used with function filter, reduce and map.
Take this example for reference but not use it.
>>> f = lambda x, y : x + y >>> f(1,1) 2
Filter function in python
As the name suggests it filter those items from the series which is true.
Filter takes function and iterable as arguments.
number = [1, 2, 3, 4, 5] def less(item): return item < 5 filter(less, number) Output: [1,2,3,4]
Reduce function in python
Take this example for reference but not use it.
>>> reduce(lambda x, y: x+y, [1, 2, 3, 4]) # the left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable.
10 # ((1+2)+3)+4)
>>> reduce(lambda x, y: x-y, [125, 25, 5, 1])
94 # ((125-25)-5)-1)
>>> reduce(lambda x, y: x*y, [2, 2, 2, 2])
16 # ((2*2)*2)*2)
>>> reduce(lambda x, y: x/y, [125, 25, 5, 1])
1 # ((125/25)/5)/1)
>>> reduce(lambda x, y: x*y, )
Map function in python
To find the square of items in a list we can use the map function in this way.
bag = [2, 6, 3, 7] def square(x): return x ** 2 list(map(square, bag)) Output: [4, 36, 9, 49]
Python List comprehension
With python list comprehension method you can create list in a comprehend way.
Let's create a demo list.
>>> list =  >>> for i in range(5): ... list.append(i**2) ... >>> list [0, 1, 4, 9, 16]
You can do the same task in a concise way. This is called list comprehension. Please look at the below example.
>>> list = [i**2 for i in range(5)] >>> list [0, 1, 4, 9, 16]
Python List comprehension of Nested list
Below is the example to show how to comprehend nested list.
>>> list = [ ... [3, 5, 2], ... [1, 9, 6], ... [7, 4, 8] ... ] >>> >>> [[column[x] for column in list] for x in range(3)] [[3, 1, 7], [5, 9, 4], [2, 6, 8]]
Convert python list to string
You can convert any python list to a string in a number of ways. But I prefer the below code. I find it very simple and useful.
>>> list = [3, 6, 7, 8, 2] >>> string = ''.join(str(x) for x in list) >>> print string 36782
join() is a string method. It concatenates each elements in a list to form a string.
This tutorial Python list examples with detailed explanation is full explanatory will help you learning about the concept of python lists in detail.