List in Python is one of the sequence data type that can store a group of elements. Some of the important points about Python list are-
- A list can store elements of different types.
- List maintains the insertion order. Elements are inserted sequentially and you can iterate them in the same order.
- One of the major difference between list and other data types like string and tuple is that list is mutable. So, it is possible to change content of a list.
- Lists can be indexed (both positive and negative) and sliced.
In this article we’ll see some of the features of the Python list, methods of the list and functions that can be used with List with examples.
Creating a list in Python
In Python list is created by grouping elements with in square brackets [], where the elements are separated by comma.
1. A list of integers.
numbers = [1, 3, 5, 7]
print(numbers) # [1, 3, 5, 7]
2. Creating empty list in Python.
alist = []
print(alist) # []
3. List with element of different types.
alist = [12, 'Sheldon', 'M', 9.99, 9.98]
print(alist)
print(type(alist[0]))
print(type(alist[1]))
print(type(alist[3]))
Output
[12, 'Sheldon', 'M', 9.99, 9.98]
<class 'int'>
<class 'str'>
<class 'float'>
As you can see type of the element at the 0th index is int, type of the element at the 1st index is str where as type of the element at the 3rd index is float.
4. Creating list using type constructor- list()
By passing an iterable in the type constructor list()
you can create a list. If no argument is given, the constructor creates a new empty list, [].
alist = list((1,2,3,4))
print(alist) #[1, 2, 3, 4]
alist = list('abcd')
print(alist) #['a', 'b', 'c', 'd']
alist = list(range(1, 9, 2))
print(alist) #[1, 3, 5, 7]
5. Creating a nested list.
You can create a list with in another list (nested list) by grouping elements enclosed in a square bracket with in a square bracket.
alist = [1, 2, [3, 4], 5, 6]
print(alist) #[1, 2, [3, 4], 5, 6]
Refer this post
List Comprehension in Python With Examples to see an elegant way to create a list using list comprehension.
Accessing Python List elements using index
List in python uses index starting from 0 to (list_length-1), it also uses negative indexing which starts at -1 from the end (right most element) and goes
till list_length.
Here is an example showing list indexing for the stored elements.
To access an element you can pass the index in the square brackets. For example to access the 5th element in a list you will pass list[4], as index starts from 0.
alist = [2, 3, 6, 7, 9]
#1st element
print(alist[0])
#last element
print(alist[4])
#last element
print(alist[-1])
#first element
print(alist[-5])
Output
2
9
9
2
Trying to pass index beyond the index range of the list results in ‘index error’. For example here is a list having 5 elements so index range for the list
is 0..4, trying to access index 5 results in an error.
alist = [2, 3, 6, 7, 9]
print(alist[5])
Output
print(alist[5])
IndexError: list index out of range
Slicing a list in Python
Just like
string slicing in Python you can do list slicing too which returns a new list.
Format of List slicing is as follows-
Listname[start_position: end_position: increment_step]
- start_position is the index from which the slicing starts, start_position is included.
- end_position is the index at which the list slicing ends, end_position is excluded.
- increment_step indicates the step size. For example if step is given as 2 then every alternate element from start_position is accessed.
All of these parameters are optional, if start_position is not specified then the slicing starts from index 0. If end_position is not specified then the slicing
ends at list_length – 1 (last index). If increment_step is not specified then increment step is 1 by default.
alist = [2, 4, 6, 8, 10]
print(alist[1:len(alist):2]) #[4, 8]
In the example start_position is 1, end_position is 5 and increment_step is 2 thus the elements at indices 1 and 3 are sliced to create another list.
alist = [2, 4, 6, 8, 10]
print(alist[::])#[2, 4, 6, 8, 10]
print(alist[-3:])#[6, 8, 10]
Iterating all elements of a list using for or while loop
1. Using for loop
alist = [2, 4, 6, 8, 10]
for i in alist:
print(i)
Output
2
4
6
8
10
As you can see from the output insertion order is maintained in the list.
2. Using while loop
alist = [2, 4, 6, 8, 10]
i = 0;
while i < len(alist):
print(alist[i])
i += 1
Output
2
4
6
8
10
Adding elements to a list
To add elements to a list you can use one of the following methods-
- list.append(x)- Add an item to the end of the list.
- list.insert(i, x)- Insert an item at a given position. The first argument is the index of the element before which to insert.
- list.extend(iterable)- Extend the list by appending all the items from the iterable.
alist = [2, 4, 6, 8, 10]
# add new element at the end
alist.append(12)
print(alist)
# insert element before index 4
alist.insert(4, 9)
print(alist)
# append elements from another list
alist.extend([14, 16])
print(alist)
Output
[2, 4, 6, 8, 10, 12]
[2, 4, 6, 8, 9, 10, 12]
[2, 4, 6, 8, 9, 10, 12, 14, 16]
Updating elements of a list in Python
Since Python list is mutable so value of the elements in the list can be modified or elements can be deleted.
To update element’s value you need to access that element using indexing or slicing and assign a new value.
alist = [2, 4, 6, 8, 10]
#Updating value of the element at 3rd index
alist[3] = 9
print(alist) #[2, 4, 6, 9, 10]
Using slicing
alist = [2, 4, 6, 8, 10]
#Updating element at 0th and 1st index
alist[0:2] = 1, 2
print(alist) #[1, 2, 6, 8, 10]
Removing element from a Python list
You can remove element from a list using one of the following method.
- list.remove(x)- Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.
- list.pop([i])- Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last
item in the list. If index is out of range then IndexError is raised.
Python list remove() method example
alist = ['h', 'e', 'l', 'l', 'o']
if 'e' in alist:
alist.remove('e')
print(alist)
Output
['h', 'l', 'l', 'o']
In the example using membership operator ‘in’ first it is checked whether the element exists in the lists or not, if it does then it is removed using remove()
method.
Python list pop() method example
alist = ['h', 'e', 'l', 'l', 'o']
elem = alist.pop(2)
print(elem)
Output
l
That's all for this topic List in Python With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
-
Concatenating Lists in Python
-
Tuple in Python With Examples
-
Named Tuple in Python
-
Python while Loop With Examples
-
Python Generator, Generator Expression, Yield Statement
You may also like-
-
Python Conditional Statement - if, elif, else Statements
-
Operator Overloading in Python
-
Python Program to Check if Strings Anagram or Not
-
raise Statement in Python Exception Handling
-
Java Collections Interview Questions And Answers
-
Volatile Keyword in Java With Examples
-
Difference Between throw And throws in Java
-
Quick Sort Program in Java