Do you want to learn Python List? How to create a list? How to add, update, and remove elements from the Python list?
This is a complete Python list tutorial for you.
You will learn the different syntaxes for performing different operations on the Python list. You will also learn the different list methods and built-in-functions you can use with Python list?
Even if you are beginners, I believe, going through this tutorial will lay the stone for mastering your Python skills. You can also bookmark this tutorial, so you can easily go through any of the syntaxes.
Let’s begin…
Table of Contents
In Python programming, the list is the data structure that stores a set of elements. This means you can save multiple elements in a single list.
Python List Syntax:
Each element in the array should be separated by a comma (,). Enclose complete list in opening and closing square bracket “[]”.
You can store any valid data type elements in the list.
Example: [‘Alice’, ‘Employee’, ‘Developer’]
Here, all the elements in the list are string data types.
It is not necessary the data type of all the elements in the list should be the same.
Example: [‘Alice’, 26, ‘Developer’]
The above example is also a valid list. The first and third elements are strings. The second element is an integer.
Some of the characteristic of Python list:
It is similar to the array in other programming languages.
Let’s see the practical Python list tutorial.
It is pretty easy. You have to add elements in the square bracket. And you don’t require any built-in-function to create Python list.
#creating empty list
listObj = []
#create list of integers
listObj = [1, 2, 3]
#creating list with mixed data types (heterogeneous list)
listObj = [1, "Hello", 3.4]
After creating a list, you can check the data type of the variable “listObj”
type(myList)
All the elements in the list are ordered and indexed. The first element will be indexed by zero, the second element will be indexed by one, and so on…
The index value will be used for accessing an element in the list.
You can print the complete list, just by its name.
listObj = ['c', 's', 'e', 's', 't', 'a', 'c', 'k']
print(listObj)
To access any specific element in the list, you have to provide an index of the element in the list.
listObj = ['c', 's', 'e', 's', 't', 'a', 'c', 'k']
print(listObj[1])
# Output: s
Suppose you have a huge number of elements in the list and you want to access the element which resides at the end of the list.
It is very difficult to count the indices of the elements residing at the end of the list.
Python has negative indexing for you.
The index of the last element is -1. The index of the second last element is -2 and so on…
listObj = ['c', 's', 'e', 's', 't', 'a', 'c', 'k']
print(listObj [-1])
# Output: k
print(listObj [-3])
# Output: a
Even for the accessing last element, you don’t need to count the index of it. This makes your job pretty easy. And Python is known for its simplicity.
If you are not interested in the complete list, you can slice the Python list using indices.
Syntax:
list[start_index: end_index]
Example:
listObj = ['c', 's', 'e', 's', 't', 'a', 'c', 'k']
# elements 3rd to 5th index
print(listObj [2:5])
#output: ['e', 's', 't']
Here you are slicing the list with the start index 2 and end index 5. It prints the element at index 2, 3, and 4. The value of end_index is not inclusive, so the element at index 5 is not printed.
How to Access the First Four Elements in the List?
By default, if you don’t mention the start_index, the value of start_index is zero.
print(listObj [:4]) #['c' 's', 'e', 's']
How to Access All Elements from the List Starting from the 4th Element?
By default, if you don’t mention the end_index, the value of end_index is the same as the index of the last element.
print(listObj [3:]) #['s', 't', 'a', 'c', 'k']
If you don’t mention the start and end index, you will get a complete Python list.
print(listObj [:])
Practically it does not make sense.
Note: You can also use the negative indexing for slicing the list.
How to find if the given element is present in the list or not?
List membership test is the test to identify if the given element is present in the list or not. If it is present, return true. Otherwise, return false.
listObj = ['c', 's', 'e', 's', 't', 'a', 'c', 'k']
print('t' in listObj )
#True
print('z' in listObj )
#False
This is a very useful Python trick in many cases where you have to choose the operations based on the presence of an element in the list.
Suppose you are maintaining the list of all the even numbers. And you found a mistake in your list. Instead of all even numbers, there is an odd number in your list.
How you can update the wrong element?
even_list = [2, 3, 6, 8]
# change the value of the 2nd element in the list.
even_list [1] = 4
print(even_list )
#[2, 4, 6, 8]
You can also use the slice syntax for changing more than one value in the list.
even_list = [2, 4, 6, 8]
# change 2nd to 4th items
even_list [1:4] = [10, 12, 14]
print(even_list )
#[2, 10, 12, 14]
There are multiple methods and ways of adding new elements to the existing Python list.
Use the append() method for adding a single element.
How to Add all the Elements from Another List?
Use the extend() method to add elements from another list to the existing list.
odd = [1, 3, 5]
odd.append(7)
print(odd)
# Output: [1, 3, 5, 7]
odd.extend([9, 11, 13])
print(odd)
# Output: [1, 3, 5, 7, 9, 11, 13]
How to Add an Element in the List at a Particular Location/Index?
We learn earlier, list preserves the ordering and every element in the list has an index.
Use the insert() method for adding a new element at a specific location in the list.
The first parameter to the insert() method will be an index where you want to add a new element. And the second parameter is the actual element you want to add.
odd = [1, 9]
odd.insert(1,3)
print(odd)
# Output: [1, 3, 9]
Note: If you provide the index out of range, it will add an element at the end of the list.
Using Indexing:
You can also use the below syntax rather than using the insert() method.
odd = [1, 3, 9]
odd[2]=5
print(odd)
# Output: [1, 3, 5, 9]
Note: Unline earlier, if you give the index out of range, your program will throw an error.
Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list assignment index out of range
Using Slice Indices:
odd=[1, 3, 9]
odd[2:2] = [5, 7]
print(odd)
# Output: [1, 3, 5, 7, 9]
Hope you find the difference between append(), extend() and insert() method for adding elements in the list.
The “del” is the new keyword you have to use.
Use the index for removing a single element from the list.
To delete multiple elements in the lust, use the slice indexing mechanism.
You can also delete the entire list.
my_list = ['p','r','o','b','l','e','m']
# delete one item
del my_list[2]
print(my_list)
# Output: ['p', 'r', 'b', 'l', 'e', 'm']
# delete multiple items
del my_list[1:5]
print(my_list)
# Output: ['p', 'm']
# delete entire list
del my_list
print(my_list)
# Error: List not defined
How to Remove Element if You Know the Value?
Now, instead of the index, you know the value of the element from the Python list.
Use remove() method.
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')
print(my_list)
# Output: ['r', 'o', 'b', 'l', 'e', 'm']
Using the pop() Method:
Instead of just deleting the element from the list, you also want to know the value of the deleted element, use the pop() method.
my_list = ['r', 'o', 'b', 'l', 'e', 'm']
print(my_list.pop(1))
# Output: 'o'
print(my_list)
# Output: ['r', 'b', 'l', 'e', 'm']
print(my_list.pop())
# Output: 'm'
print(my_list)
# Output: ['r', 'b', 'l', 'e']
Note: If you don’t provide an index to the pop() method, it removes and returns the last element from the list.
How to Delete all the Elements in the List?
Use clear() method. Instead of deleting the list, it deleted all the elements in the list. It returns an empty list.
my_list = ['p' 'r', 'o', 'b', 'l', 'e', 'm']
my_list.clear()
print(my_list)
# Output: []
Deleting Elements in a List by Assigning Empty Value:
Yeah, you can do that.
my_list = ['p','r','o','b','l','e','m']
my_list[2:3] = []
print(my_list)
#output: ['p', 'r', 'b', 'l', 'e', 'm']
my_list[2:5] = []
print(my_list)
#output: ['p', 'r', 'm']
Do you want to perform certain operations on each element in the given list?
You can iterate over a complete list using ‘for’ keyword.
for dev in ['Alice','Bob','Mark']:
print(dev, "is a developer.")
Output:
Alice is a developer. Bob is a developer. Mark is a developer.
You can use enumerate() built-in function.
for ind, dev in enumerate(['Alice', 'Bob', 'Mark']):
print(ind, dev)
Output:
0 Alice 1 Bob 2 Mark
Note: Index starts with zero.
You can use the join() method. It is a string method to covert the Python list into a string.
myList=['I', 'love', 'Python', 'Programming.']
print(" ".join(myList))
Output:
I love Python Programming.
Make sure, all the elements in the array list are strings.
If the elements in the list are integer you have to convert it to a string before using join() method.
For example, if the input is [1, 3, 5, 5], the output should be 1355.
Here is a simple solution for your query.
myList=[1, 3, 5, 5]
print("Origional List: ",myList)
#converting data type of each element in the list
#from int to string.
strList=[str(x) for x in myList]
print("String List: ",strList)
val = int(" ".join(strList))
print("Integer Value: "val)
Output:
Origional List: [1, 3, 5, 5] String List: ['1', '3', '5', '5'] Integer Value: 1355
There are two ways you can sort the Python list.
sorted() built-in function:
>> listObj=[34,17,56] sorted(listObj) [17, 34, 56] >> listObj [34, 17, 56]
sort() Python list method:
>> listObj=[34,17,56] >> sorted(listObj, reverse=True) [56, 34, 17]
There are a lot of differences between the two sorting methods. I have explained it in the list sorting tutorial.
Here, we need to compare two lists. There are various methods we can use to check if the two lists have the same elements or not.
As we have already discuss, you can refer to this tutorial.
When you add a complete Python list as an element of another list, it is called a nested list.
The syntax is pretty easy.
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
How to access elements in the nested list?
# nested list
nestedListObj = ["Happy",23, [2,7,1,5]]
print(nestedListObj [2][1])
# Output: 7
What are the Python list methods?
We saw all the list methods used for inserting, deleting, and updating the Python list. Summarizing those methods for comparative understanding.
List methods for For adding new elements:
List methods for deleting elements:
Other useful list methods:
What are the built-in-function you can use with the Python list?
There are some built-in functions where you can pass the list as an argument and get the specific operation done with just one line.
Some Mathematical Operations on Python List using Built-in Functions:
>>> listObj=[34,56,56] >>> len(listObj) 3 >>> max(listObj) 56 >>> min(listObj) 34 >>> sum(listObj) 146
It is an advanced topic in the Python list.
What is list compression?
In simple terms, list compression is a technique where we write an expression followed by for statement inside square brackets.
Don’t get it?
No worry.
Check this example.
Write a program to create a list of first 5 even numbers.
multiplyOfTwo = [] for x in range(5):
multiplyOfTwo.append(2 *x)
print(multiplyOfTwo)
Output:
[0, 2, 4, 6, 8]
Instead of writing those multiple lines, you can do the same job with just one line of code using the list comprehension technique.
multiplyOfTwo = [2 * x for x in range(5)]
You can also add more conditions in a list comprehension.
pow2 = [2 ** x for x in range(5) if x > 0]
print(pow2)
Output:
[2, 4, 6, 8]
Based on the if-condition, this program only includes values which are greater than zero.
This is all about Python list tutorial. I have tested each code and spent a really good amount of time curating this complete this tutorial. If you like it, please write to me in the comment section and also share with your friends.
Some of the Python list programming examples:
If you enjoy and learn from this Python tutorial, I believe, you will also like my Python dictionary tutorial. Just like a Python list, you will find everything you need to learn about Python dictionary.
If you have any specific question, write in the comment section. I’m here for you 😀
Hi Aniruddha
This function isn’t working for me what you showed in theory section :
>>> sum(listObj)
146
I am trying to code one stuff in pycharm but getting no output
numbers=[12,14]
sum(numbers)
output:
=======
C:\Users\mkar\PycharmProjects\test\venv\Scripts\python.exe C:/Users/mkar/PycharmProjects/test/testing.py
Process finished with exit code 0
Hi Madhumaya,
Looks like you are able to run the program but you are not printing anything as an output.
If you are running the Python code from .py flle, use print() function.
———–
numbers=[12,14]
print(sum(numbers))
———-
Save this code in your .py file and execute.
Hi Aniruddha Chaudhari, Very exhaustive and complete list. Keep it up. Look forward to other curated list on python.
Thanks, Suhas and very glad you like it. Here is another Python dictionary tutorial I curated. Hope you enjoy it too.
Hi Aniruddha Chaudhari, Supper explanation I just want to say thank you for this tutorial.
You’re welcome, Martin. I’m glad you like it.
hi,
You have a problem here. pls, check it.
the second false should be true.
best regards
Alireza
Hi Alireza,
Thanks for the correction. We have updated this tutorial addressing this correction.
Best wishes!