Lists in Python

Python Tutorial: Nail PYTHON LIST In 10 Min, List trick.

Picture of topictrick
topictrick
Welcome to python tutorial on 'Python Lists. You'll learn the basics of lists in python with example. You'll learn about list append, list pop, list extend, list count, list reverse, list copy, etc methods.

Table of Contents

Introduction to Python Lists.

Hola and welcome to today’s Python Tutorial on “Python lists and its functions“. In this, tutorial you’ll learn the basics of python lists and its various function with example. Python lists are similar to an array of programming language but “Lists in Python” are more powerful in terms of functionality and are flexible in usage.

Lists in Python.

All programming language used data structure to store and manipulate data. The List data type in python is similar to array in C++ or Java or Python or Tables in COBOL.

A Python Lists can be used to store, manipulate and retrieve data element as per business requirements. You can store different types (i.e. string and integer data) of data elements in the lists and lists can grow dynamically in memory.

In laymen term, A list is similar to an array that consists of a group of elements or items. Just like an array, a list can store elements. But, there is one major difference between an array and a Python List. An array can store one kind of data whereas a list can store different type of the data. Thus, Python Lists are more versatile abd useful than array. List in Python are most widely used datatypes in Python program.

Python Lists are easy to define and flexible to use in Python programs. In order to define a list in python, you need to enclosed data items in between square brackets. You can also use various list function to add, append, remove, update, search and delete data items from the Python Lists.

Python Lists can grow dynamically in memory. But the size of any array is fixed and they cannot expand during the run time.

Python Lists can store different types of data i.e. (String or Numeric), but in the array you can only store a single type of data at a time.

Python List
Python List

How Python Lists Works?

Imagine you went to a shopping mall for shopping grocery items. Each time you pick an item from the shelf you scan it with the scanner before placing the item into your basket. The scanning machine stores the scanned item into machine memory.

It also displays the list of items on the screen in the order in which item was scanned. You can visualize this scanner machine as a ‘Python list’ which is storing items in a sequence after being scanned on the machine.

In the following example, shp_lst is a Python List which will store the name of purchase items, every time you scan an item with scanning machine, the item is added/appended to list shp_lst and index is updated.

You can access these store items from shp_lst list by using python for .. loop or by other python functions and accessing list item is pretty simple and straight forward. You will learn to perform various operation on lists in later part of the Python Tutorial

How Python List Works
How Python List Works

Python Lists and List functions.

Lists in Python are primarily used to store data in a sequence. A list is a list in itself and it can store different type of data. Lists in python are defined by square brackets and each data item is separated by ‘,’ comma-delimited. Python list provides many in-build functions that can be used to manipulate data in the lists. Now, let’s discuss all lists function in details:

Example 1: How to create lists in Python?

# Define an empty Lists in Python.
shp_lst = []
# Define Lists in Python with integer items only.
shp_lst = [123, -123, 9, 48, 34]
# Define Lists in Python with strings items only.
shp_lst = ['tea', 'coffee', 'sugar', 'salt']
# Define Lists in Python with mixed items.
shp_lst = ['tea', 'coffee', 'sugar', 'salt', 34]
# Print Python Lists elements.
print(shp_lst)
['tea', 'coffee', 'sugar', 'salt', 34]

Example 2: Python range() Function to create lists.

# Python range() function.
num_lst = list(range(1,10,1))
num_lst 
[1, 2, 3, 4, 5, 6, 7, 8, 9] 

Example 3: For loop to create Python lists.

# Python for loop function.
a = []
for i in range(1,10,1):
a.append(i)
print ('Print List Value:' a) 
[1, 2, 3, 4, 5, 6, 7, 8, 9] 

Example 4: Update the elements of lists.

# Update first element of the lists.
a = [1, 2, 3, 4]
a[0] = 2
[2, 2, 3, 4] 

Example 5: Concatenate two python lists.

# Concatinate two Python lists.
a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
print ('Concatinate List :', (a+b))
Concatinate List : [1, 2, 3, 4, 5, 6, 7, 8] 

How to get individual items in a the list with Indexes and Slicing?

By now you have understood that list in python is a sequence data sets. You can store a similar value of different values as per requirements and you know that each item has an associated index.

You can use this index to access lists values. Python Lists start with zero and index is incremented by one every time an item is added or appended to the list. The process of creating a new python list from an existing list is termed as slicing operations.

Slicing represents extracting a piece of the list by mentioning starting and ending position numbers.

Syntax :: list_name [start_position : end_position : step size]

  • list_name – Name of existing list variable.
  • start_position – starting index position.
  • end_position – end of index position.
  • step size – the gap between items, the default step size is 1.

Example 2: Python Lists Indexing and Slicing.

# Create shp_lst shopping Lists in Python.
shp_lst = ['tea', 'coffee', 'sugar', 'salt']
# Print third element of the shp_lst list.
shp_lst[3]
'salt'
# Print the second and third element of the shp_lst list.
shp_lst[1:3]
['coffee', 'sugar']
# Create a new List from the existing shp_lst List.
shp_lst_sl = shp_lst[1:4]
shp_lst_sl
['coffee', 'sugar', 'salt']
# Print last 2 items of the shp_lst List using negative indexes.
shp_lst[-2:5]
['sugar', 'salt']
Lists in Pythons
Lists in Pythons

Python Lists and Function.

As you know, Lists in Python are a powerful data set and are equally flexible to use. Python Lists provides many additional function/methods that can be used to perform many data manipulation operations on the lists. Let’s discuss all these functions one by one with examples:

Python List Append Method.

The Python List append method is used to append items at the end of the list. In the following example, a new item would be added to the list.

list.append(x)

# Create shopping shp_lst Lists in Python.
shp_lst = ['tea', 'coffee', 'sugar', 'salt']
# Append jam item to the shp_lst Lists.
shp_lst.append('jam')
# Print the items of the lists.
shp_lst
['tea', 'coffee', 'sugar', 'salt', 'jam']

Python List Extend Method.

The Python List extends method is used to append all items from another list. In the following example, all items from shp_ext_lst will be added to the existing shopping list.

list.extend(iterable)

# Create shp_lst Lists in Python.
shp_lst = ['tea', 'coffee', 'sugar', 'salt']
# Append items from shp_ext_lst List to the shp_lst List.
shp_ext_lst = ['jam','pepper']
shp_lst.extend(shp_ext_lst)
# Print the List (shp_lst).
shp_lst
['tea', 'coffee', 'sugar', 'salt', 'jam', 'pepper']

Python List Insert Method.

The Python List insert method is used to insert an item at a specific location in the list. You need to specify the position where you want to insert value in the list.

list.insert(i, x)

# Create shp_lst shopping Lists in Python.
shp_lst = ['tea', 'coffee', 'sugar', 'salt']
# Insert a new item at the second position.
shp_lst.insert(1,'jam')
# Print the shopping list (shp_lst).
shp_lst
['tea', 'jam', 'coffee', 'sugar', 'salt']

Python List Remove Method.

The Python List Remove method is used to remove the item from the Python list. You need to specify the value that you want to drop from the list. Also, if your list has duplicate value then remove method will only remove first value and will retain second value. If the value is not present in the list then it will throw an error (i.e. list.remove(x): x not in list).

list.remove(x)

# Create Programming Language lists in Python.
pgm_lst = ['COBOL', 'CICS', 'PYTHON', 'JAVA']
# Remove item from the pgm_lst list.
pgm_lst.remove('CICS')
# Print the programming language list (pgm_lst).
pgm_lst
['COBOL', 'PYTHON', 'JAVA']
# Programming Language lists in Python.
pgm_lst = ['COBOL', 'CICS', 'PYTHON', 'JAVA', 'JAVA']
# Remove an item from the list.
pgm_lst.remove('JAVA')
# Print the programming language list (pgm_lst).
pgm_lst
['COBOL', 'CICS', 'PYTHON', 'JAVA']

Python List Pop Method.

The Python List POP method is to remove the specific item from the list. You are required to specify the position of the item as a parameter.

list.pop([i])

# Create programming language pgm_lst Lists in Python.
pgm_lst = ['COBOL', 'CICS', 'PYTHON', '.NET']
# Drop list last data item.
pgm_lst.pop()
# Print the programming list (pgm_lst).
pgm_lst
['COBOL', 'CICS', 'PYTHON']
# Programming language lists in Python.
pgm_lst = ['COBOL', 'CICS', 'PYTHON', '.NET', 'JAVA']
# Remove specific item from the list.
pgm_lst.pop(3)
# Print the programming language list (pgm_lst).
pgm_lst
['COBOL', 'CICS', 'PYTHON', 'JAVA']

Python List Clear Method.

The Python List clear method is used to clear items from the lists.

list.clear()

# Programming Language lists in Python.
pgm_lst = ['COBOL', 'CICS', 'PYTHON', '.NET']
# Clear item from the list.
pgm_lst.clear()
# Print the programming list (pgm_lst).
pgm_lst
[]

Python List Index Method.

The Python List Index method is used to get the index of the item. You are required to specify the item name as a parameter. If the item is not present in the list then it will throw an error message.

list.index(x[, start[, end]])

# Programming Language lists in Python.
pgm_lst = ['COBOL', 'CICS', 'PYTHON', '.NET']
# Get index of the item from the list.
pgm_lst.index('CICS')
1

Python List Count Method.

The Python List Count method is used to get the count of specific items in the list. You need to specify the item as an argument.

list.count(x)

# Programming Language lists in Python.
pgm_lst = ['COBOL', 'CICS', 'PYTHON', '.NET']
# Clear item from the list.
pgm_lst.count('COBOL')
1

Python List Sort Method.

The Python List Sort method is used to arrange items in the list. Python list sort has two parameters i.e. Key=None and reverse=False.

list.sort(key=None, reverse=False)

# Programming Language lists in Python.
pgm_lst = ['COBOL', 'CICS', 'PYTHON', '.NET']
# Sort item in the list.
pgm_lst.sort()
pgm_lst
['.NET', 'CICS', 'COBOL', 'PYTHON']
# Sort item in the list.
pgm_lst.sort(key=None,reverse=True)
pgm_lst
['PYTHON', 'COBOL', 'CICS', '.NET']

Python List Reverse Method.

The Python List Reverse method is used to reverse the order of items in the list.

list.reverse()

# Programming Language lists in Python.
pgm_lst = ['COBOL', 'CICS', 'PYTHON', '.NET']
# Reverse the order of items in the list.
pgm_lst.reverse()
pgm_lst
['.NET', 'PYTHON', 'CICS', 'COBOL']

Python List Copy Method.

The Python Lists copy method is used to copy an item from one list to others.

list.copy()

# Programming Language lists in Python.
pgm_lst = ['COBOL', 'CICS', 'PYTHON', '.NET']
# Reverse the items sequence in the list.
a = pgm_lst.copy()
a
['COBOL', 'CICS', 'PYTHON', '.NET']

Python List Sum Function.

The Python Lists sum method is used to retrieve the sum of all elements of the list.

list.sum()

# Programming Language lists in Python.
a_lst = [1, 2, 3, 4, 5, 6]
# Get sum of all items.
print('The sum of all list items :', sum(a_lst))

Lists in Python Live Coding Demo.

Conclusion.

Finally, we reach an end of today’s tutorial on List in Python. By now, you have understood the basics of Lists in Python. You’ve also learned about various inbuilt function for performing various data manipulation operations. In our next python tutorial, you will learn more about Tuple. If you like our tutorial, please don’t forget to share with your friend and family and do leave your valuable feedback. Your comments are valuable to us.