Python ProgrammingPython Programming

Python Lists

In this tutorial you will learn, to generate and manage lists in Python programming.

A list in Python is much the same thing as an array in Java or C or any other language; it's an ordered collection of objects. List is one of the most commonly used built-in data structures, for storing a collection of values. List can contain heterogeneous values such as integers, floats, strings, tuples, lists, and dictionaries but they are commonly used to store collections of homogeneous objects. Python lists are mutable sequences.
Lists should always be used when we want to store items in some kind of order. The keys for a list are integers.


Create and Print

A list is created by putting element values inside a square bracket. To reuse our list, we can give it a name and store it like this.

Example
The following program shows how to create lists of different data-types:
intList = [10, 20, 30, 40]
strList = ["Canada", "Japan", "London"]
mixList = ["Canada", 20, True, 500.50]
generate = [x + 6 for x in [4, 5, 6]]  # Generate from loop
listfromtuple = list((5, 13, 15, 17, 29))  # List from a tuple
python = list('python')  # List from a string
 
print(intList)
print(strList)
print(mixList)
print(generate)
print(listfromtuple)
print(python)
Output
[10, 20, 30, 40]
['Canada', 'Japan', 'London']
['Canada', 20, True, 500.5]
[10, 11, 12]
[5, 13, 15, 17, 29]
['p', 'y', 't', 'h', 'o', 'n']

Access List Items

To access any list item you need to refer it by it's index number.

Example
The following program shows how to fetch list items:
testList = ["Canada", "Japan", "London"]
print(testList[0])
print(testList[1])
print(testList[2])
Output
Canada
Japan
London

Change List Item Value

To update the value of a specific item, need to refer it by it's index number.

Example
The following program shows how to update value of list items:
testList = ["Canada", "Japan", "London"]
print(testList)
 
testList[0] = "Germany"
testList[1] = 100
print(testList)
Output
['Canada', 'Japan', 'London']
['Germany', 100, 'London']

Loop Over List

You can iterate list items by using a for loop.

Example
Print all items of a list:
testList = ["Canada", "Japan", "London", "Germany", "Africa"]
 
for item in testList:
    print(item)
 
Output
Canada
Japan
London
Germany
Africa

Check if Item Exists

To verify if a specified item is exist in a list use the in keyword.

Example
Check if "Japan" exist in the list:
testList = ["Canada", "Japan", "London", "Germany", "Africa"]
 
if "Japan" in testList:
    print("Yes")
Output
Yes

List Length

You can use len() method, to get total number of items in a list.

Example
Print the count of items in the list:
testList = ["Canada", "Japan", "London", "Germany", "Africa"]
print(len(testList))
Output
5

Add Item at End

The append() method used to append an item at the end of list.

Example
"Africa" added at the end of list:
testList = ["Canada", "Japan", "London", "Germany"]
print(testList)
 
testList.append("Africa")
print(testList)
Output
['Canada', 'Japan', 'London', 'Germany']
['Canada', 'Japan', 'London', 'Germany', 'Africa']

Add Item at Specific Position

You can use insert() method, to add an item at the specified index.

Example
New list item added in first position:
testList = ["Canada", "Japan", "London", "Germany"]
print(testList)
 
testList.insert(1, "Africa")
print(testList)
Output
['Canada', 'Japan', 'London', 'Germany']
['Canada', 'Africa', 'Japan', 'London', 'Germany']

Remove specific List Item

You can use remove() method, to delete or remove specified item from a list. The pop() method removes the specified index item if passed or the last item of list.

Example
testList = ["Canada", "Japan", "London", "Germany"]
print(testList)
 
testList.remove("Japan")  # Japan removed
print(testList)
 
testList.pop(1)  # London removed
print(testList)
 
testList.pop()  # Last item removed
print(testList)
 
Output
['Canada', 'Japan', 'London', 'Germany']
['Canada', 'London', 'Germany']
['Canada', 'Germany']
['Canada']

Clear and Delete List

The clear() method truncate the list and del() keyword delete the list.

Example
testList = ["Canada", "Japan", "London", "Germany"]
testList.clear()
print(testList)
 
del testList

Concatenate Lists

You can use + operator or extend() method to concatenate two or more lists.

Example
Print the merged list items:
list1 = ["Canada", "Japan"]
list2 = ["London", "Germany"]
 
list3 = list1 + list2
print(list3)
 
mergedlist = []
mergedlist.extend(list1)
mergedlist.extend(list2)
print(mergedlist)
Output
['Canada', 'Japan', 'London', 'Germany']
['Canada', 'Japan', 'London', 'Germany']

Tricks of List Slicing

Python slicing is a computationally fast way to methodically access parts of your data. The colons (:) in subscript notation make slice notation - which has the optional arguments, start, stop, step.

Example
Various slicing tricks
items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 
print(items[4:])  # From index 4 to last index
 
print(items[:4])  # From index 0 to 4 index
 
print(items[4:7])  # From index 4(included) up to index 7(excluded)
 
print(items[:-1])  # Excluded last item
 
print(items[:-2])  # Up to second last index(negative index)
 
print(items[::-1])  # From last to first in reverse order(negative step)
 
print(items[::-2])  # All odd numbers in reversed order
 
print(items[-2::-2])  # All even numbers in reversed order
 
print(items[::])  # All items
 
Output
[4, 5, 6, 7, 8, 9]
[0, 1, 2, 3]
[4, 5, 6]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[0, 1, 2, 3, 4, 5, 6, 7]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
[9, 7, 5, 3, 1]
[8, 6, 4, 2, 0]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Get First and Last Item

You can use slicing notation to fetch first and last item of list.

Example
testList = ["Canada", "Japan", "London", "Germany", "Africa", "Italy"]
 
print(testList[0])  # First item
print(testList[-1])  # Last item
Output
Canada
Italy

Remove Duplicate List Items

Example
testList = ["Canada", "Japan", "Canada", "Germany", "Japan", "Italy"]
print(testList)
 
cleanlist = []
[cleanlist.append(x) for x in testList if x not in cleanlist]
print(cleanlist)
 
Output
['Canada', 'Japan', 'Canada', 'Germany', 'Japan', 'Italy']
['Canada', 'Japan', 'Germany', 'Italy']

Difference Between two Lists

The set() method commonly used to get a unique collection of items.

Example
list1 = ["Canada", "Japan", "Canada", "Germany", "Japan", "Italy"]
list2 = ["Germany", "France", "Poland", "Italy", "India", "London"]
 
sub1 = list(set(list1) - set(list2))
print(sub1)
 
sub2 = list(set(list2) - set(list1))
print(sub2)
Output
['Canada', 'Japan']
['India', 'France', 'Poland', 'London']

Shuffle List

random.shuffle() returns the shuffled result as a new list.

Example
import random
 
listItems = ["Canada", "Japan", "France", "Germany", "Italy", "Poland"]
print(listItems)
 
random.shuffle(listItems, random.random)
print(listItems)
 
Output
['Canada', 'Japan', 'London', 'Germany']
['Canada', 'Africa', 'Japan', 'London', 'Germany']