- Python Basics
- Python Tutorial
- Python Applications
- Python Versions
- Python environment setup
- Python Basic Syntax
- Python end (end=)
- Python sep (sep=)
- Python Comments
- Python Identifiers
- Python Variables
- Python Operators
- Python Ternary Operator
- Python Operator Precedence
- Python Control and Decision
- Python Decision Making
- Python if elif else
- Python Loops
- Python for Loop
- Python while Loop
- Python break Statement
- Python continue Statement
- Python pass Statement
- Python break vs. continue
- Python pass vs. continue
- Python Built-in Types
- Python Data Types
- Python Lists
- Python Tuples
- Python Sets
- Python frozenset
- Python Dictionary
- List vs. Tuple vs. Dict vs. Set
- Python Numbers
- Python Strings
- Python bytes
- Python bytearray
- Python memoryview
- Python Misc Topics
- Python Functions
- Python Variable Scope
- Python Enumeration
- Python import Statement
- Python Modules
- Python operator Module
- Python os Module
- Python Date and Time
- Python Exception Handling
- Python File Handling
- Python Advanced
- Python Classes and Objects
- Python @classmethod Decorator
- Python @staticmethod Decorator
- Python Class vs. Static Method
- Python @property Decorator
- Python Keywords
- Python Keywords
- Python and
- Python or
- Python not
- Python True
- Python False
- Python None
- Python in
- Python is
- Python as
- Python with
- Python yield
- Python return
- Python del
- Python from
- Python lambda
- Python assert
- Python Built-in Functions
- Python All Built-in Functions
- Python print() Function
- Python input() Function
- Python int() Function
- Python len() Function
- Python range() Function
- Python str() Function
- Python ord() Function
- Python chr() Function
- Python read()
- Python write()
- Python open()
- Python Examples
- Python Examples
List in Python (with Examples)
This post includes all of the descriptions and details for an important topic, "list in Python," as well as example programs and their outputs. In this post, I attempted to cover the entire "list" concept. The following are the topics that will be covered in this post:
- What is a list in Python?
- Create an empty list in Python
- Create a list with values in Python
- Create and print a list in Python
- Print list items using the "for" loop in Python
- Find and print the length of a list in Python
- List slicing (forward) in Python
- List slicing (backward) in Python
- Append a new element to a list in Python
- Replace elements in a list in Python
- Add two lists in Python
- Remove elements from a list in Python
- List method in Python
- Nested list in Python
- List comprehension in Python
What is a list in Python?
List in Python is a built-in data type used to store multiple items in a single variable. That is, when we need to store a collection of data in a single variable, then we use lists.
Note: List items are ordered, changeable, and allow duplicates.
List items being ordered means that all the items (elements or values) on the list are numbered. For example, if there is a list named mylist, then mylist[0] refers to the first element, whereas mylist[1] refers to the second element, and so on.
List items are changeable, which means that we can change the items of the list after initialization.
List items allow duplicate values, which means that in a particular list, there may be two or more items with the same value.
Create an empty list in Python
An empty list can be created in the following two ways:
- Using square brackets. That is, []
- Using the list() constructor
Create an empty list using square brackets
Here is the syntax to create an empty list in Python, using the square bracket:
listName = []
Create an empty list using the list() constructor
To create an empty list using the list() constructor, use the following syntax:
listName = list()
Create a list with values in Python
Here is the syntax to create a list with values in Python:
listName = [value1, value2, value3, ..., valueN]
where value1, value2, value3, etc. can be of any data type such as integer, floating-point, boolean, string, character, etc., or it can be a list too.
Another way that we can create a list is by using the list() constructor is:
listName = list((value1, value2, value3, ..., valueN))
Note: Keep the double bracket in mind.
Create and print a list in Python
This is the first example of this article on the list. This example program creates a list and then prints the list as it is on the output screen.
mylist = [1, 2, 3, 4, 5] print(mylist) mylist = [1, 'c', True, "fresherearth", 12.4, 43] print(mylist)
The same program can also be created in this way:
mylist = list((1, 2, 3, 4, 5)) print(mylist) mylist = list((1, 'c', True, "fresherearth", 12.4, 43)) print(mylist)
The snapshot given below shows the output produced by the above Python code.
As already mentioned, the list is a kind of built-in data type in Python. The list can be used to store multiple values in a single variable, as shown in the program given above. That is, the values 1, 2, 3, 4, and 5 are initialized to a single variable, say mylist, using the first statement. Similar things are done to define a list using the third statement.
List items are indexed so that the first item is stored at the 0th index, the second at the 1st index, and so on.
Can a list contain elements of different types?
Yes, of course. List elements may be of the same or different types. Here is an example:
x = [12, 'c', 32.54, "codes", True] print(x)
The output should be:
[12, 'c', 32.54, 'codes', True]
Python Access and Print List Element using Index
The elements of a list can be accessed using its index, either through forward indexing or through backward (negative) indexing. The snapshot given below shows both forward and backward indexing.
That is, to access the very first element of a list named mylist, we need to use mylist[0], whereas to access the last element of a list, we need to use mylist[-1]. Here is an example showing how to access and print the list elements using forward indexing.
mylist = [1, 2, 3, 4, 5] print(mylist[0]) print(mylist[1]) print(mylist[2]) print(mylist[3]) print(mylist[4])
The output produced by this Python program should be:
1 2 3 4 5
Here is another program showing how we access elements of a list using backward indexing:
mylist = [1, 2, 3, 4, 5] print(mylist[-1]) print(mylist[-2]) print(mylist[-3]) print(mylist[-4]) print(mylist[-5])
Here is the output that this program produced:
5 4 3 2 1
I know the above program looks weird, because if there are more elements in the list, then writing the print() statement along with the index number for all the elements is not possible and also takes too much time. Therefore, we need to use a loop to print list elements. The example program based on it is given below.
Print list items using the "for" loop in Python
This program does the same job as the previous program. The only difference is its approach. That is, this program uses a "for" loop to do the job:
mylist = [1, 2, 3, 4, 5] for element in mylist: print(element)
You'll get the same output as the previous program's output.
Print all list elements on a single line using a "for" loop
Most of the time, we need to print all list elements on a single line. Therefore, this program shows how to code in Python so that the list elements get printed on a single line instead of multiple:
mylist = [1, 2, 3, 4, 5] for element in mylist: print(element, end=" ")
Here is its output:
1 2 3 4 5
Note: The "end" parameter is used to skip insertion of an automatic newline when printing.
Python: Create and Print a List with User Input
Now let's create another example program on lists that allows users to define the size and elements of a list. The defined list elements will get printed back on the output screen:
print("How many element to store in the list: ", end="") n = int(input()) print("Enter", n, "elements for the list: ", end="") mylist = [] for i in range(n): val = input() mylist.append(val) print("\nThe list is:") for i in range(n): print(mylist[i], end=" ")
A sample run with user input of 5 as the size of the list and 10, 20, 30, 40, and 50 as its five elements is shown in the snapshot given below:
Find and print the length of a list in Python
The len() function plays an important role in most of the programs in Python when working with lists, especially when working with a list whose elements are defined by the user at run-time of the program. Because in that case, the function len() finds the length of the list, and that length plays, of course, a crucial role most of the time. Let's take a look at one of the simplest examples, which uses the len() function:
mylist = [1, 2, 3, 4, 5] print("\nLength of List =", len(mylist))
Following is its sample output:
Length of List = 5
Another way to find and print the length of a list without using the len() method is to:
mylist = [1, 2, 3, 4, 5] count = 0 for element in mylist: count = count+1 print("\nList contains", count, "items.")
The output produced by the above program is:
List contains 5 items.
List slicing (forward) in Python
Here is the syntax to slice a list in Python:
listVariable[startIndex, endIndex, step]
where "startIndex" is the starting index number from where the slice should start. The element at this index is included. The "endIndex" is the last index number at which the slice should stop. The element at this index is excluded. And the "step" is used when we need to slice items from a list, along with skipping every nth element in between while slicing.
Note: By default, the startIndex value is 0, the endIndex value is equal to the length of the list, and the step value is equal to 1.
Before considering an example of list slicing in Python, Let's have a look at the following list:
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Now:
- mylist[0:] returns [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- mylist[:] returns [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- mylist[:10] returns [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- mylist[2:4] returns [3, 4]
- mylist[2:8:3] returns [3, 6]
- mylist[2:9:3] returns [3, 6, 9]
- mylist[::3] returns [1, 4, 7, 10]
Now here is an example of list slicing in Python. This program sliced a list named "mylist" in multiple ways, so that all the concepts of list slicing (forward) will easily get cleared using a single program:
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print("The original list is:") print("mylist =", mylist) print("\nList slicing example:") print("mylist[0:] =", mylist[0:]) print("mylist[:] =", mylist[:]) print("mylist[:10] =", mylist[:10]) print("mylist[2:4] =", mylist[2:4]) print("mylist[2:8:3] =", mylist[2:8:3]) print("mylist[2:9:3] =", mylist[2:9:3]) print("mylist[::3] =", mylist[::3])
The snapshot given below shows the sample output produced by the above Python code on list slicing:
List slicing (backward) in Python
The element at index -1 will be considered the last element of the list, whereas the element at index "-lengthOfList" will be considered the first element of the list. Here is an example of list slicing using negative indexing:
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print("The original list is:") print("mylist =", mylist) print("\nList slicing example (using backward indexing):") print("mylist[-10:] =", mylist[-10:]) print("mylist[-8:] =", mylist[-8:]) print("mylist[:] =", mylist[:]) print("mylist[:-1] =", mylist[:-1]) # second index's value is excluded print("mylist[:-4] =", mylist[:-4]) print("mylist[-4:-2] =", mylist[-4:-2]) print("mylist[-8:-2:3] =", mylist[-8:-2:3]) print("mylist[-9:-2:3] =", mylist[-9:-2:3]) print("mylist[-10:-1:3] =", mylist[-10:-1:3]) print("mylist[::3] =", mylist[::3])
A sample run of the above Python code is shown in the snapshot given below:
Append a new element to a list in Python
We can add required elements to a list at any time because list items are changeable. Elements can be added either at the end of a list or at a given index. Let's start with adding an element of a list at the end of a list in Python.
Add a New Element at the End of a List
The append() method is used when we need to add an element at the end of a list. Here is an example:
mylist = [1, 2, 3, 4, 5] print("The original list is:") print("mylist =", mylist) print("\nEnter an Element to add: ", end="") element = int(input()) mylist.append(element) print("\nNow the list is:") print("mylist =", mylist)
The snapshot given below shows the sample run of the above Python program, with user input 10 as an element to add:
Insert a New Element at the Given Index into a List
The insert() method is used when we need to insert an element at a specified index in a list. Here is an example:
mylist = [1, 2, 3, 4, 5] print("The original list is:") print("mylist =", mylist) print("\nEnter an Element to add: ", end="") element = int(input()) print("At what index ? ", end="") index = int(input()) if index <= len(mylist): mylist.insert(index, element) print("\nNow the list is:") print("mylist =", mylist) else: print("\nInvalid Index Number!")
A sample run with user input of 500 as an element and 3 as an index number to add a new element to the list is shown in the snapshot given below:
Here is another example that shows how an element can be added to a list at a certain index.
mylist = ['c', 'o', 'd', 's', 'c'] print("The original list is:") print("mylist =", mylist) mylist.insert(3, 'e') print("\n1. Now the list is:") print("mylist =", mylist) mylist.insert(6, 'r') print("\n2. Now the list is:") print("mylist =", mylist) mylist[7:10] = ['a', 'c', 'k', 'e'] print("\n3. Now the list is:") print("mylist =", mylist) mylist.insert(11, 'r') print("\n4. Now the list is:") print("mylist =", mylist)
To add an element at a particular index without removing the previous value available at that index, use insert(). While using insert() to insert an element at the specified index, all the elements after that index moved one index forward.
Replace elements in a list in Python
To add new elements to a list, use direct initialization of a single or multiple values to a single or multiple indexes. However, the element(s) are replaced with those available at the index(es) used for initialization. Here is its sample program, demonstrating the concept:
mylist = ['c', 'o', 'd', 's', 'c'] print("The original list is:") print("mylist =", mylist) mylist[3] = 'x' print("\n1. Now the list is:") print("mylist =", mylist) mylist[3:5] = ['e', 's'] print("\n2. Now the list is:") print("mylist =", mylist) mylist[6:12] = ['c', 'r', 'a', 'c', 'k', 'e', 'r'] print("\n3. Now the list is:") print("mylist =", mylist) mylist[3] = 'x' print("\n4. Now the list is:") print("mylist =", mylist) mylist[2:8] = 'z' print("\n5. Now the list is:") print("mylist =", mylist) mylist[1:6] = ['a', 'b'] print("\n6. Now the list is:") print("mylist =", mylist) mylist[:] = 'x' print("\n7. Now the list is:") print("mylist =", mylist)
Let's concentrate on the output of the above program to get the concept.
The original list is: mylist = ['c', 'o', 'd', 's', 'c'] 1. Now the list is: mylist = ['c', 'o', 'd', 'x', 'c'] 2. Now the list is: mylist = ['c', 'o', 'd', 'e', 's'] 3. Now the list is: mylist = ['c', 'o', 'd', 'e', 's', 'c', 'r', 'a', 'c', 'k', 'e', 'r'] 4. Now the list is: mylist = ['c', 'o', 'd', 'x', 's', 'c', 'r', 'a', 'c', 'k', 'e', 'r'] 5. Now the list is: mylist = ['c', 'o', 'z', 'c', 'k', 'e', 'r'] 6. Now the list is: mylist = ['c', 'a', 'b', 'r'] 7. Now the list is: mylist = ['x']
Add Multiple Elements to the End of a List at the Same Time
The extend() function is used when we need to add multiple elements at the end of a list without converting the list into a nested list. Here is an example:
mylist = [1, 2, 3] mylist.extend([4, 5]) print(mylist)
[1, 2, 3, 4, 5]
Add two lists in Python
The + operator helps with the addition of the two lists. Below is an example of list addition in Python:
listOne = ['p', 'y', 't'] listTwo = ['h', 'o', 'n'] listThree = listOne + listTwo print(listThree) listOne = listOne + listTwo print(listOne)
Here is its sample output:
['p', 'y', 't', 'h', 'o', 'n'] ['p', 'y', 't', 'h', 'o', 'n']
Remove elements from a list in Python
Like adding an element to a list, sometimes we also need to remove an element from a list. The list element can be removed in either of the two ways:
- using the remove() method
- using the pop() method
Using remove(), you can remove an element from a list
The remove() method is used when we need to remove an element from a list, using the element's value.
mylist = [11, 22, 33, 44, 55] print("The list is:") print(mylist) mylist.remove(44) print("\nNow the list is:") print(mylist)
The output is:
The list is: [11, 22, 33, 44, 55] Now the list is: [11, 22, 33, 55]
Using pop(), you can remove an element from a list.
The pop() method is used when we need to pop an element from a list, using the element's index.
mylist = [11, 22, 33, 44, 55] print("The list is:") print(mylist) mylist.pop(3) print("\nNow the list is:") print(mylist)
You'll get the same output as the previous program's output.
Using the del keyword, you can delete multiple items from a list at once
The "del" keyword is used when we need to delete multiple elements from a list. The keyword del can also be used to delete the whole list. Here is an example:
x = ['p', 'y', 't', 'h', 'o', 'n'] print(x) del x[1] print(x) del x[1:4] print(x) del x
The output should be:
['p', 'y', 't', 'h', 'o', 'n'] ['p', 't', 'h', 'o', 'n'] ['p', 'n']
After using the "del x" statement, the whole list "x" gets deleted. And if you try to print "x," then the program produces an error like this:
List method in Python
These are the functions that can be used while working with lists in Python. All these functions are important from a "list" point of view. All of these functions have been described in very brief terms. You can learn more in depth by visiting its dedicated post.
- list() converts a sequence to a list
- len() returns the length of a list.
- append() is used to add a new element at the end of a list.
- extend() is used to add multiple elements or an iterable at the end of a list.
- insert() inserts an element at the specified index.
- remove() removes the first occurrence of an element with a specified value from a list.
- pop() is used to remove an item from the list.
- max() returns the maximum item in an iterable or the maximum between or among two or more arguments.
- min() returns the minimum item in an iterable, or the minimum between or among two or more arguments.
- clear() is used to empty the list.
- index() returns the index number of the first occurrence of a specified value in a list.
- count() returns the number of occurrences of a particular element in a list.
- sort() is used to sort a list.
- sorted() returns the sorted list.
- reverse() is used to reverse the elements of a list.
- reversed() returns the reversed list.
- copy() is used to copy a list.
Nested list in Python
A list can be nested inside another list. That is, when we add a list itself instead of an element, when initializing the elements to a list, then the list becomes a nested list. Here is an example:
mylist = [1, [2, 3, 4], 5, 6, [7, 8, 9, 10]] print("Direct:") print(mylist) print("\nUsing loop:") for x in mylist: print(x)
Here is its sample output:
Direct: [1, [2, 3, 4], 5, 6, [7, 8, 9, 10]] Using loop: 1 [2, 3, 4] 5 6 [7, 8, 9, 10]
Here's another nested list (list of list(s)) example:
mylist = [1, [2, 3, 4], 5, 6, [7, 8, 9, 10]] print(mylist[0]) print(mylist[1][0]) print(mylist[1][1]) print(mylist[1][2]) print(mylist[2]) print(mylist[3]) print(mylist[4][0]) print(mylist[4][1]) print(mylist[4][2]) print(mylist[4][3])
This is the last example of a nested list, or list of lists, in Python. This program uses a list named books_list, in which all the elements are themselves lists of two elements each.
books_list = [["Java", "$128"], ["C++", "$99"], ["Python", "$169"]] ch = None while ch != "3": print("\n1. Show Books List") print("2. Add a Book") print("3. Exit") print("Enter Your Choice (1-3): ", end="") ch = input() if ch == "1": print("\nBook\t\t Price") for book in books_list: book_name, book_price = book print(book_name, "\t\t", book_price) elif ch == "2": print("\nEnter the Name of Book: ", end="") book_name = input() print("Enter the Price: ", end="") book_price = input() book_price = "$" + book_price add_book = book_name, book_price books_list.append(add_book) elif ch == "3": print("\nOk!") break else: print("\nInvalid Choice!")
The sample run is shown in the snapshot given below:
List comprehension in Python
The word "comprehension" means the ability to understand something. After understanding the list, it becomes easy to understand the list comprehension topic.
Generally, professional Python programmers use list comprehension the most because it allows them to create a list with multiple elements in a single or a few statements. In short, list comprehension is a concise way to create a list.
Definition: A list comprehension is an expression available inside a square bracket. The expression employs a "for" loop to construct a list via list comprehension.
Python List Comprehension Syntax
Here is the syntax to create a list using list comprehension:
mylist = [expression for item in iterable if condition == True]
The if condition == True is optional.
Python List Comprehension Example
Here is an example of a list comprehension. This program creates a list named "tableOf2" with 10 elements:
tableOf2 = [2 * i for i in range(1, 11)] print(tableOf2)
If this program is run, the following output will be produced:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Here is another example of list comprehension. The table of 1, 2, 3,..., 10 is printed using list comprehension in this program.
for num in range(1, 11): table = [num * i for i in range(1, 11)] print(table)
The output should be:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] [3, 6, 9, 12, 15, 18, 21, 24, 27, 30] [4, 8, 12, 16, 20, 24, 28, 32, 36, 40] [5, 10, 15, 20, 25, 30, 35, 40, 45, 50] [6, 12, 18, 24, 30, 36, 42, 48, 54, 60] [7, 14, 21, 28, 35, 42, 49, 56, 63, 70] [8, 16, 24, 32, 40, 48, 56, 64, 72, 80] [9, 18, 27, 36, 45, 54, 63, 72, 81, 90] [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Here is the last example of list comprehension. This program uses conditions in the expression of list comprehension:
mylist = [x for x in range(100) if x<10] print(mylist)
Here is its output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The method range() returns a sequence of numbers from 0 to 99. However, all 0s, 1, 2, 3,... 99s less than 10 are initialized as elements of a list called mylist.
« Previous Tutorial Next Tutorial »