Python Lists

08 Jul, 2022
Lists are just like dynamically sized arrays, declared in other languages (vector in C++ and ArrayList in Java). In a simple language, a list is a collection of things, enclosed in [ ] and separated by commas. Lists are the simplest containers that are an integral part of the Python language. Lists need not be homogeneous always which makes it the most powerful tool in Python. A single list may contain DataTypes like Integers, Strings, as well as Objects. Lists are mutable, and hence, they can be altered even after their creation.
List in Python are ordered and have a definite count. The elements in a list are indexed according to a definite sequence and the indexing of a list is done with 0 being the first index. Each element in the list has its definite place in the list, which allows duplicating of elements in the list, with each element having its own distinct place and credibility.
Note: Lists are a useful tool for preserving a sequence of data and further iterating over it.
Table of content: 
Creating a List
Knowing the size of the List
Adding Elements to a List: Using append() methodUsing insert() methodUsing extend() method
Using append() method
Using insert() method
Using extend() method
Accessing elements from the List
Removing Elements from the List: Using remove() methodUsing pop() method
Using remove() method
Using pop() method
Slicing of a List
List Comprehension
Operations on List
List Methods
Lists in Python can be created by just placing the sequence inside the square brackets[]. Unlike Sets, a list doesn’t need a built-in function for the creation of a list. 
Note: Unlike Sets, the list may contain mutable elements.  
Python3
# Python program to demonstrate# Creation of List  # Creating a ListList = []print("Blank List: ")print(List)  # Creating a List of numbersList = [10, 20, 14]print("\nList of numbers: ")print(List)  # Creating a List of strings and accessing# using indexList = ["Geeks", "For", "Geeks"]print("\nList Items: ")print(List[0])print(List[2])  # Creating a Multi-Dimensional List# (By Nesting a list inside a List)List = [['Geeks', 'For'], ['Geeks']]print("\nMulti-Dimensional List: ")print(List)
Blank List: 
[]

List of numbers: 
[10, 20, 14]

List Items: 
Geeks
Geeks

Multi-Dimensional List: 
[['Geeks', 'For'], ['Geeks']]
Time Complexity: O(1)
Space Complexity: O(n)
A list may contain duplicate values with their distinct positions and hence, multiple distinct or duplicate values can be passed as a sequence at the time of list creation.
Python3
# Creating a List with# the use of Numbers# (Having duplicate values)List = [1, 2, 4, 4, 3, 3, 3, 6, 5]print("\nList with the use of Numbers: ")print(List)  # Creating a List with# mixed type of values# (Having numbers and strings)List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks']print("\nList with the use of Mixed Values: ")print(List)
List with the use of Numbers: 
[1, 2, 4, 4, 3, 3, 3, 6, 5]

List with the use of Mixed Values: 
[1, 2, 'Geeks', 4, 'For', 6, 'Geeks']
Python3
# Creating a ListList1 = []print(len(List1))  # Creating a List of numbersList2 = [10, 20, 14]print(len(List2))
0
3
Python3
f = [1, 1, 2, 3, 5, 8]p = [2, 3, 5, 7]grading = ["Tests", "Quizzes", "Individual Labs", "Group Labs", "Hackathons"]grades = [300, 60, 120, 60, 120]oddjob = [1, 5.6, True, 4-7j, "Hello", [1, 2], [3.9, "World"]]print(len(grading))print(sum(f), sum(p))
5
20 17
Python3
grading = ["Tests", "Quizzes", "Individual Labs", "Group Labs", "Hackathons"]grades = [300, 60, 120, 60, 120]oddjob = [1, 5.6, True, 4-7j, "Hello", [1, 2], [3.9, "World"]]# We access individual elements using the index# The first element is at index 0print(grades[1], oddjob[4])# We access the elements from the back using negative indices# -1 is the last, -2 is the last but one and so onprint(grading[-1], grading[-3])print(max(grades), min(grades))
60 Hello
Hackathons Individual Labs
300 60
We can take input of a list elements as string, integer, float, etc. But the default one is a string.
Python3
# Python program to take space separated input as a string# split and store it to a list and print the string list  # input the list as stringstring = input("Enter elements of a list (Space-Separated): ")lst = string.split()  # split the strings and store it to a listprint('The list is:', lst)   # printing the list  #This code is contributed by Susobhan AKhuli
Output:
Enter elements of a list (Space-Separated): GEEKS FOR GEEKS
The list is: ['GEEKS', 'FOR', 'GEEKS']
Python
# Python program to store integrs in a list in one line  # input size of the listn = int(input("Enter the size of list : "))# store integrs in a list using map, split and strip functionslst = list(map(int, input("Enter the integer elements of list(Space-Separated): ").strip().split()))[:n]print('The list is:', lst)   # printing the list  #This code is contributed by Susobhan AKhuli
Output:
Enter the size of list : 4
Enter the integer elements of list(Space-Separated): 6 3 9 10
The list is: [6, 3, 9, 10]
To know more see this.
Elements can be added to the List by using the built-in append() function. Only one element at a time can be added to the list by using the append() method, for the addition of multiple elements with the append() method, loops are used. Tuples can also be added to the list with the use of the append method because tuples are immutable. Unlike Sets, Lists can also be added to the existing list with the use of the append() method.
Python3
# Python program to demonstrate# Addition of elements in a List  # Creating a ListList = []print("Initial blank List: ")print(List)  # Addition of Elements# in the ListList.append(1)List.append(2)List.append(4)print("\nList after Addition of Three elements: ")print(List)  # Adding elements to the List# using Iteratorfor i in range(1, 4):    List.append(i)print("\nList after Addition of elements from 1-3: ")print(List)  # Adding Tuples to the ListList.append((5, 6))print("\nList after Addition of a Tuple: ")print(List)  # Addition of List to a ListList2 = ['For', 'Geeks']List.append(List2)print("\nList after Addition of a List: ")print(List)
Initial blank List: 
[]

List after Addition of Three elements: 
[1, 2, 4]

List after Addition of elements from 1-3: 
[1, 2, 4, 1, 2, 3]

List after Addition of a Tuple: 
[1, 2, 4, 1, 2, 3, (5, 6)]

List after Addition of a List: 
[1, 2, 4, 1, 2, 3, (5, 6), ['For', 'Geeks']]
Time Complexity: O(1)
Space Complexity: O(1)
append() method only works for the addition of elements at the end of the List, for the addition of elements at the desired position, insert() method is used. Unlike append() which takes only one argument, the insert() method requires two arguments(position, value). 
Python3
# Python program to demonstrate # Addition of elements in a List   # Creating a ListList = [1,2,3,4]print("Initial List: ")print(List)  # Addition of Element at # specific Position# (using Insert Method)List.insert(3, 12)List.insert(0, 'Geeks')print("\nList after performing Insert Operation: ")print(List)
Initial List: 
[1, 2, 3, 4]

List after performing Insert Operation: 
['Geeks', 1, 2, 3, 12, 4]
Time Complexity: O(n)
Space Complexity: O(1)
Other than append() and insert() methods, there’s one more method for the Addition of elements, extend(), this method is used to add multiple elements at the same time at the end of the list.
Note: append() and extend() methods can only add elements at the end.
Python3
# Python program to demonstrate# Addition of elements in a List  # Creating a ListList = [1, 2, 3, 4]print("Initial List: ")print(List)  # Addition of multiple elements# to the List at the end# (using Extend Method)List.extend([8, 'Geeks', 'Always'])print("\nList after performing Extend Operation: ")print(List)
Initial List: 
[1, 2, 3, 4]

List after performing Extend Operation: 
[1, 2, 3, 4, 8, 'Geeks', 'Always']
Time Complexity: O(n)
Space Complexity: O(1)
In order to access the list items refer to the index number. Use the index operator [ ] to access an item in a list. The index must be an integer. Nested lists are accessed using nested indexing. 
Python3
# Python program to demonstrate# accessing of element from list  # Creating a List with# the use of multiple valuesList = ["Geeks", "For", "Geeks"]  # accessing a element from the# list using index numberprint("Accessing a element from the list")print(List[0])print(List[2])  # Creating a Multi-Dimensional List# (By Nesting a list inside a List)List = [['Geeks', 'For'], ['Geeks']]  # accessing an element from the# Multi-Dimensional List using# index numberprint("Accessing a element from a Multi-Dimensional list")print(List[0][1])print(List[1][0])
Accessing a element from the list
Geeks
Geeks
Accessing a element from a Multi-Dimensional list
For
Geeks
In Python, negative sequence indexes represent positions from the end of the array. Instead of having to compute the offset as in List[len(List)-3], it is enough to just write List[-3]. Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second-last item, etc.
Python3
List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks']  # accessing an element using# negative indexingprint("Accessing element using negative indexing")  # print the last element of listprint(List[-1])  # print the third last element of listprint(List[-3])
Accessing element using negative indexing
Geeks
For
Time Complexity: O(1)
Space Complexity: O(1)
A list can be reversed by using the (.reverse) method.
Python3
# Reversing a listmylist = [1, 2, 3, 4, 5, 'Geek', 'Python']mylist.reverse()print(mylist)
['Python', 'Geek', 5, 4, 3, 2, 1]
Elements can be removed from the List by using the built-in remove() function but an Error arises if the element doesn’t exist in the list. Remove() method only removes one element at a time, to remove a range of elements, the iterator is used. The remove() method removes the specified item.
Note: Remove method in List will only remove the first occurrence of the searched element.
Python3
# Python program to demonstrate# Removal of elements in a List  # Creating a ListList = [1, 2, 3, 4, 5, 6,        7, 8, 9, 10, 11, 12]print("Initial List: ")print(List)  # Removing elements from List# using Remove() methodList.remove(5)List.remove(6)print("\nList after Removal of two elements: ")print(List)  # Removing elements from List# using iterator methodfor i in range(1, 5):    List.remove(i)print("\nList after Removing a range of elements: ")print(List)
Initial List: 
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

List after Removal of two elements: 
[1, 2, 3, 4, 7, 8, 9, 10, 11, 12]

List after Removing a range of elements: 
[7, 8, 9, 10, 11, 12]
Time Complexity: O(n)
Space Complexity: O(1)
pop() function can also be used to remove and return an element from the list, but by default it removes only the last element of the list, to remove an element from a specific position of the List, the index of the element is passed as an argument to the pop() method.
Python3
List = [1, 2, 3, 4, 5]  # Removing element from the# Set using the pop() methodList.pop()print("\nList after popping an element: ")print(List)  # Removing element at a# specific location from the# Set using the pop() methodList.pop(2)print("\nList after popping a specific element: ")print(List)
List after popping an element: 
[1, 2, 3, 4]

List after popping a specific element: 
[1, 2, 4]
Time Complexity: O(1)/O(n) (O(1) for removing the last element, O(n) for removing the first and middle elements)
Space Complexity: O(1)
We can get substrings and sublists using a slice. In Python List, there are multiple ways to print the whole List with all the elements, but to print a specific range of elements from the list, we use the Slice operation. Slice operation is performed on Lists with the use of a colon(:). To print elements from beginning to a range use [: Index], to print elements from end-use [:-Index], to print elements from specific Index till the end use [Index:], to print elements within a range, use [Start Index: End Index] and to print the whole List with the use of slicing operation, use [:]. Further, to print the whole List in reverse order, use [::-1].
Note – To print elements of List from rear-end, use Negative Indexes. 
 
UNDERSTANDING SLICING OF LISTS:
pr[0] accesses the first item, 2.
pr[-4] accesses the fourth item from the end, 5.
pr[2:] accesses [5, 7, 11, 13], a list of items from third to last.
pr[:4] accesses [2, 3, 5, 7], a list of items from first to fourth.
pr[2:4] accesses [5, 7], a list of items from third to fifth.
pr[1::2] accesses [3, 7, 13], alternate items, starting from the second item.
Python3
# Python program to demonstrate# Removal of elements in a List  # Creating a ListList = ['G', 'E', 'E', 'K', 'S', 'F',        'O', 'R', 'G', 'E', 'E', 'K', 'S']print("Initial List: ")print(List)  # Print elements of a range# using Slice operationSliced_List = List[3:8]print("\nSlicing elements in a range 3-8: ")print(Sliced_List)  # Print elements from a# pre-defined point to endSliced_List = List[5:]print("\nElements sliced from 5th "      "element till the end: ")print(Sliced_List)  # Printing elements from# beginning till endSliced_List = List[:]print("\nPrinting all elements using slice operation: ")print(Sliced_List)
Initial List: 
['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']

Slicing elements in a range 3-8: 
['K', 'S', 'F', 'O', 'R']

Elements sliced from 5th element till the end: 
['F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']

Printing all elements using slice operation: 
['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']
Python3
f = [1, 1, 2, 3, 5, 8]print(f)print(f[2:7])print(f[2:11:3])print(f[::-1])
[1, 1, 2, 3, 5, 8]
[2, 3, 5, 8]
[2, 8]
[8, 5, 3, 2, 1, 1]
Python3
# Creating a ListList = ['G', 'E', 'E', 'K', 'S', 'F',        'O', 'R', 'G', 'E', 'E', 'K', 'S']print("Initial List: ")print(List)  # Print elements from beginning# to a pre-defined point using SliceSliced_List = List[:-6]print("\nElements sliced till 6th element from last: ")print(Sliced_List)  # Print elements of a range# using negative index List slicingSliced_List = List[-6:-1]print("\nElements sliced from index -6 to -1")print(Sliced_List)  # Printing elements in reverse# using Slice operationSliced_List = List[::-1]print("\nPrinting List in reverse: ")print(Sliced_List)
Initial List: 
['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']

Elements sliced till 6th element from last: 
['G', 'E', 'E', 'K', 'S', 'F', 'O']

Elements sliced from index -6 to -1
['R', 'G', 'E', 'E', 'K']

Printing List in reverse: 
['S', 'K', 'E', 'E', 'G', 'R', 'O', 'F', 'S', 'K', 'E', 'E', 'G']
List comprehensions are used for creating new lists from other iterables like tuples, strings, arrays, lists, etc. A list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element. 
Syntax:
newList = [ expression(element) for element in oldList if condition ]
Example: 
Python3
# Python program to demonstrate list# comprehension in Python  # below list contains square of all# odd numbers from range 1 to 10odd_square = [x ** 2 for x in range(1, 11) if x % 2 == 1]print(odd_square)
[1, 9, 25, 49, 81]
For better understanding, the above code is similar to as follows: 
Python3
# for understanding, above generation is same as,odd_square = []  for x in range(1, 11):    if x % 2 == 1:        odd_square.append(x**2)  print(odd_square)
[1, 9, 25, 49, 81]
Refer to the below articles to get detailed information about List Comprehension.
Python List Comprehension and Slicing
Nested List Comprehensions in Python
List comprehension and ord() in Python
Find the length of a list
Iterate over a list in Python
Concatenating two lists in Python
List Membership Test
The operations mentioned above modify the list Itself.
Do go through recent articles on Lists
Creating a 3D List
Iterate over a list in Python
Iterate over multiple lists simultaneously
Internal working of list in Python
Python Slicing
Using lists as Stacks
Using lists as Queues
Python List Comprehensions vs Generator Expressions
List Methods in Python – Set 1 Set 2
Lambda expression and filter function
Useful Links: 
Recent Articles on Python List
Python Tutorials
Python Output Programs in List: Set 6, Set 11, Set 12, Set 13
Multiple Choice Questions
All articles in Python Category
More on lists
saifi_zakir
VidushiAgrawal
cffjob
nikhilaggarwal3
RajuKumar19
simranarora5sos
akshaysingh98088
kumaripunam984122
vinayaka2000
anvesha19jain
sarajadhav12052009
susobhanakhuli
santeswar
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Iterate over a list in Python