In this tutorial, we'll learn everything about Python lists: creating lists, changing list elements, removing elements, and other list operations with the help of examples.,We can delete one or more items from a list using the Python del statement. It can even delete the list entirely.,Lists are mutable, meaning their elements can be changed unlike string or tuple.,List comprehension is an elegant and concise way to create a new list from an existing list in Python.
Python lists are one of the most versatile data types that allow us to work with multiple elements at once. For example,
# a list of programming languages['Python', 'C++', 'JavaScript']
In Python, a list is created by placing elements inside square brackets []
, separated by commas.
# list of integers my_list = [1, 2, 3]
A list can have any number of items and they may be of different types (integer, float, string, etc.).
# empty list my_list = [] # list with mixed data types my_list = [1, "Hello", 3.4]
Nested lists are accessed using nested indexing.
my_list = ['p', 'r', 'o', 'b', 'e'] # first item print(my_list[0]) # p # third item print(my_list[2]) # o # fifth item print(my_list[4]) # e # Nested List n_list = ["Happy", [2, 0, 1, 5]] # Nested indexing print(n_list[0][1]) print(n_list[1][3]) # Error!Only integer can be used for indexing print(my_list[4.0])
Output
p
o
e
a
5
Traceback (most recent call last):
File "<string>", line 21, in <module>
TypeError: list indices must be integers or slices, not float
Last Updated : 01 Aug, 2022
Output:
["Geeks", "for", "Geeks"]
Blank List: [] List of numbers: [10, 20, 14] List Items: Geeks Geeks
Blank List: [] List of numbers: [10, 20, 14] List Items: Geeks Geeks
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']
Accessing a element from the list
Geeks
Geeks
Accessing a element from a Multi - Dimensional list
For
Geeks
sea_creatures = ['shark', 'cuttlefish', 'squid', 'mantis shrimp', 'anemone']
When we print out the list, the output responds exactly like the list we created:
print(sea_creatures)
print(sea_creatures)
Output['shark', 'cuttlefish', 'squid', 'mantis shrimp', 'anemone']
print(sea_creatures[1])
Outputcuttlefish
The index numbers for this list range from 0
-4
, as shown in the table above. So to call any of the items individually, we would refer to the index numbers like this:
sea_creatures[0] = 'shark'
sea_creatures[1] = 'cuttlefish'
sea_creatures[2] = 'squid'
sea_creatures[3] = 'mantis shrimp'
sea_creatures[4] = 'anemone'
List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.,A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it. For example, this listcomp combines the elements of two lists if they are not equal:,It is sometimes tempting to change a list while you are looping over it; however, it is often simpler and safer to create a new list instead.,Note that in Python, unlike C, assignment inside expressions must be done explicitly with the walrus operator :=. This avoids a common class of problems encountered in C programs: typing = in an expression when == was intended.
>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'] >>> fruits.count('apple') 2 >>> fruits.count('tangerine') 0 >>> fruits.index('banana') 3 >>> fruits.index('banana', 4) # Find next banana starting a position 4 6 >>> fruits.reverse() >>> fruits['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange'] >>> fruits.append('grape') >>> fruits['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape'] >>> fruits.sort() >>> fruits['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear'] >>> fruits.pop() 'pear'
>>> stack = [3, 4, 5] >>> stack.append(6) >>> stack.append(7) >>> stack[3, 4, 5, 6, 7] >>> stack.pop() 7 >>> stack[3, 4, 5, 6] >>> stack.pop() 6 >>> stack.pop() 5 >>> stack[3, 4]
>>> from collections import deque >>> queue = deque(["Eric", "John", "Michael"]) >>> queue.append("Terry") # Terry arrives >>> queue.append("Graham") # Graham arrives >>> queue.popleft() # The first to arrive now leaves 'Eric' >>> queue.popleft() # The second to arrive now leaves 'John' >>> queue # Remaining queue in order of arrival deque(['Michael', 'Terry', 'Graham'])
>>> squares = [] >>> for x in range(10): ...squares.append(x ** 2) ... >>> squares[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
squares = list(map(lambda x: x ** 2, range(10)))
squares = [x ** 2 for x in range(10) ]
Python provides the remove() function which is used to remove the element from the list. Consider the following example to understand this concept.,Lists maintain the order of the element for the lifetime. That's why it is the ordered collection of objects.,Consider the following example in which, we are taking the elements of the list from the user and printing the list on the console.,Both lists have consisted of the same elements, but the second list changed the index position of the 5th element that violates the order of lists. When compare both lists it returns the false.
<class 'list'>
<class 'list'>
False
True
printing employee data...
Name : John, ID: 102, Country: USA
printing departments...
Department 1:
Name: CS, ID: 11
Department 2:
Name: IT, ID: 11
HOD Details ....
CS HOD Name: Mr. Holding, Id: 10
IT HOD Name: Mr. Bewon, Id: 11
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
<class 'list'>
1
2
3
4
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[3, 4, 5]
[2, 4, 6]
5
[3, 4, 5]
[1, 2, 3, 4]
[3, 4]
Lists respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new list, not a string.,In fact, lists respond to all of the general sequence operations we used on strings in the prior chapter.,The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. Important thing about a list is that items in a list need not be of the same type.,You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator, and you can add to elements in a list with the append() method. For example −
Creating a list is as simple as putting different comma-separated values between square brackets. For example −
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5];
list3 = ["a", "b", "c", "d"]
#!/usr/bin/python list1 = ['physics', 'chemistry', 1997, 2000]; list2 = [1, 2, 3, 4, 5, 6, 7]; print "list1[0]: ", list1[0] print "list2[1:5]: ", list2[1: 5]
When the above code is executed, it produces the following result −
list1[0]: physics
list2[1: 5]: [2, 3, 4, 5]
#!/usr/bin/python list1 = ['physics', 'chemistry', 1997, 2000]; print list1 del list1[2]; print "After deleting value at index 2 : " print list1
When the above code is executed, it produces following result −
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2: ['physics', 'chemistry', 2000]