LA ILAHA ILLA HU
Allah, Your Lord There Is No Deity Except Him.
Lesson 22: Lists In Python
In Python Lists are used to store multiple items in a single variable. Lists are created using square brackets. Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage. List items are ordered, changeable, and allow duplicate values. List items are indexed, the first item has index [0], the second item has index [1] etc.Example1 of List
thislist = ["pineapple", "banana", "cherry, apple"]
print(thislist)
output will be
['pineapple', 'banana', 'cherry', 'apple']
Example 2
marks = [81, 87, 90]
print(marks)
output will be
[81, 87, 90]
To print marks for an indiidual subject put sq bkts in print(marks[]) within sq bkts
specify the position for eg if we put 0 we get 81 if we put 1 we get 87 and if we put
2 we get 90 int the above eg remember python is a 0 index language i.e. it starts indexing
with o.
example a
marks = [81, 87, 90]
print(marks[0])
the output for the above is
81
examples b
marks = [81, 87, 90]
print(marks[1])
the output for the above is
87
examples c
marks = [81, 87, 90]
print(marks[2])
the output for the above is
90
Also remember that in python the counting can also begin from in reverse order i.e.
Example
marks = [81, 87, 90]
print(marks[-1])
the out put for the above is
90
You can also get marks only for starting two index position.
Example
marks = [81, 87, 90]
print(marks[0:2])
the out put for the above will be.
[81, 87]
Using for loops in list
the output for above will be
81
87
90
Adding New Items to List
for adding new item or marks to the list append new marks as under it will be added as the last item in the list.Example
marks = [81, 87, 90]
marks.append(98)
print(marks)
the out put will be
[81, 87, 90, 98]
For adding new item or marks to the list in the begining use insert functions as under it will be added as the first item in the list.
marks = [81, 87, 90]
marks.insert(0, 98)
print(marks)
the output for above will be
[98, 81, 87, 90]
To check if a particular mark exist in list.
Example
marks = [81, 87, 90]
marks.insert(0, 98)
print(87 in marks)
the output for abvoe will be
True
To check the length of list to ascertain the total no of items.
Example
marks = [81, 87, 90]
marks.insert(0, 98)
print(len(marks))
the output for abvoe will be
4
Allow Duplicates
Since lists are indexed, lists can have items with the same value i.e. lists Allow Duplicates.
Example
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
output will be
['apple', 'banana', 'cherry', 'apple', 'cherry']
List Length: How to determine how many items a list has?
To determine how many items a list has, use the len() function.
Example: Print the number of items in the list
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(len(thislist))
outout will be
5
Data Types of a List Items can be of any data type inluding String, int and boolean data types.
Example
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
print(list1)
print(list2)
print(list3)
outout will be
['apple', 'banana', 'cherry']
[1, 5, 7, 9, 3]
[True, False, False]
Example: A list with strings, integers and boolean values
mylist1 = ["abc", 34, True, 40, "male", 30, "female"]
print(mylist1)
output will be
['abc', 34, True, 40, 'male', 30, 'female']
type(): From Python's perspective, lists are defined as objects with the data type class 'list'
Example
mylist = ["apple", "banana", "cherry"]
print(type(mylist))
output will be
<class 'list'>
The list() Constructor
You can creat a new list using the list() constructor.
Example
thislist = list(("apple", "banana", "orange", "cherry"))
# note the double round-brackets
print(thislist)
output will be
['apple', 'banana', 'orange', 'cherry']
Access List Items: How to Access List Items?
Access Items; In Python List items are indexed and you can access them by referring to the index number.
Example: Print the second item of the list.
thislist = ["apple", "banana", "orange", "cherry"]
print(thislist[2])
output will be
orange
Note: The first item has index 0.
Negative Indexing: Negative indexing means start from the end
Example: -1 refers to the last item, -2 refers to the second last item etc.
Print the last item of the list
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
output will be
cherry
Range of Indexes:
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new list with the specified items.
Example1: Return the third, fourth, and fifth item
list1 = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(list1[2:5])
output will be
['cherry', 'orange', 'kiwi']
Explanation
Return the items from position 2 to 5
Remember that the first item is position 0,
and note that the item in position 5 is NOT included
The search will start at index 2 (included) and end at index 5 (not included).
Example2:
By leaving out the start value, the range will start at the first item
This example returns the items from the beginning to, but NOT including, "kiwi"
list1 = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(list1[:4])
output will be
['apple', 'banana', 'cherry', 'orange']
Explanation
This will return the items from index 0 to index 4.
Remember that index 0 is the first item, and index 4 is the fifth item
Remember that the item in index 4 is NOT included
Example3:
By leaving out the end value, the range will go on to the end of the list.
list1 = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(list1[2:])
output will be
['cherry', 'orange', 'kiwi', 'melon', 'mango']
Explanation
This will return the items from index 2 to the end.
Remember that index 0 is the first item, and index 2 is the.
Range of Negative Indexes
If you want to start the search from the end of the list.
Example: This example returns the items from "orange" (-4) to, but NOT including "mango" (-1)
list1 = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(list1[-4:-1])
output will be
['orange', 'kiwi', 'melon']
Explanation
Negative indexing means starting from the end of the list.
This example returns the items from index -4 (included) to index -1 (excluded)
Remember that the last item has the index -1.
Check if Item Exists: How to Check if Item Exists In the List
You can use keyword to determine if a specified item is present in a list.
Example: Check if "apple" is present in the list.
output will be
Yes, 'apple' is in the fruits list
Change List Items: How to Change List Items?
You can change the value of a specific item by refering to the index number.
Example1: Change the second item.
listA = ["apple", "banana", "orange", "cherry"]
listA[1] = "pineapple"
print(listA)
output will be
['apple', 'pineapple', 'orange', 'cherry']
Example2:
Change the values "banana" and "orange" with the values "pineapple" and "grapes"
listA = ["apple", "banana", "orange", "cherry"]
listA[1:3] = ["pineapple", "grapes"]
print(listA)
output will be
['apple', 'pineapple', 'grapes', 'cherry']
Example2:
In the above example if you want to change the last value also as "dates simply do not specify the end range.
listA = ["apple", "banana", "orange", "cherry"]
listA[1:] = ["pineapple", "grapes", "dates"]
print(listA)
output will be
['apple', 'pineapple', 'grapes', 'dates']
Explanation
Note; as the end range i.e.[1:] is not specified the value "cherry"" has also been replace with "dates".
Example3:
Change the second value by replacing it with two new values.
listA = ["apple", "banana", "orange", "cherry"]
listA[1:2] = ["pineapple", "grapes"]
print(listA)
output will be
['apple', 'pineapple', 'grapes', 'orange', 'cherry']
Example4: Change the second and third value by replacing it with one value.
listA = ["apple", "banana", "orange", "cherry"]
listA[1:3] = ["grapes"]
print(listA)
output will be
['apple', 'grapes', 'cherry']
Insert Items: How to insert a new list item, without replacing any of the existing values, we can use the insert() method.
The insert() method will inserts an item at the specified index.
Example: Insert "grapes" as the third item.
listA = ["apple", "banana", "orange", "cherry"]
listA.insert(2, "grapes")
print(listA)
output will be
['apple', 'banana', 'grapes', 'orange', 'cherry']
Note: The list will now contain 5 items.
Add List Items: How to Add List Items?
In order to add items to list you can Append Items, To add an item to the end of the list, use the append() method.
Example: Using the append() method to append an item to list.
listA = ["apple", "banana", "cherry"]
listA.append("grapes")
print(listA)
output will be
['apple', 'banana', 'cherry', 'grapes']
Insert Items: To insert a list item at a specified index, use the insert() method.
The insert() method will inserts an item at the specified index.
Example: Insert an item at the second position in the list below.
listA = ["apple", "banana", "grapes", "cherry"]
listA.insert(1, "dates")
print(listA)
output will be
['apple', 'dates', 'banana', 'grapes', 'cherry']
Note: The lists now contains 5 items.
Extend List: To append elements from another list to the current list, use the extend() method.
Example: Add the elements of listB to listA.
listA = ["apple", "banana", "cherry", "grapes"]
listB = ["mango", "pineapple", "papaya", "dates"]
listA.extend(listB)
print(listA)
output will be
['apple', 'banana', 'cherry', 'grapes', 'mango', 'pineapple', 'papaya', 'dates']
Note: The elements of listB have been added to the end of the listA.
Add Any Iterable: You can add any iterable object tuples, sets, dictionaries etc to a list.
The extend() method does not have to append list, any iterable object tuples, sets, dictionaries etc can be added to a list.
Example: Add elements of a tuple to a list.
listA = ["apple", "banana", "cherry", "grapes"]
tuple1 = ("kiwi", "orange", "mango", "pineapple", "papaya", "dates")
listA.extend(tuple1)
print(listA)
output will be
['apple', 'banana', 'cherry', 'grapes', 'kiwi', 'orange', 'mango', 'pineapple', 'papaya', 'dates']
Note: The elements of tuple1 have been added to the end of the listA.
Remove List Items: How to Remove List Items?
Remove Specified Item: The remove() method removes the specified item.
Example1:Remove "apple" from the list below.
listA = ["apple", "banana", "cherry", "grapes"]
listA.remove("apple")
print(listA)
output will be
['banana', 'cherry', 'grapes']
The pop() method: Remove Specified Index using pop() method it will remove the item at the specified index.
Example2: Remove the third item fro the list below.
listA = ["apple", "banana", "cherry", "grapes"]
listA.pop(2)
print(listA)
output will be
['apple', 'banana', 'grapes']
Note: If you do not specify the index position, the pop() method removes the last item.
Example3: Remove the last item.
listA = ["apple", "banana", "cherry", "grapes"]
listA.pop()
print(listA)
output will be
['apple', 'banana', 'cherry']
Example4: The del keyword also removes the specified index.
listA = ["apple", "banana", "cherry", "grapes"]
del listA[0]
print(listA)
output will be
['banana', 'cherry', 'grapes']
Example5: The del keyword can also delete the list completely.
listA = ["apple", "banana", "cherry", "grapes"]
del listA
print(listA)
output will be
This will cause an error because you have succsesfully deleted "thislist".( NameError: name 'listA' is not defined )
Clear the List: How to cear the list?
The clear() method empties the list. The list still remains, but it has no content.
Example: Clear the list content.
listA = ["apple", "banana", "cherry", "grapes"]
listA.clear()
print(listA)
output will be
[]
Lists: How to Loop Through a List?
You can loop through the list items by using a for loop.
Example: Print all items in the list, one by one.
output will be
apple
banana
cherry
grapes
How to Loop Through the Index Numbers?
Example; Print all items by referring to their index number.
output will be
apple
banana
cherry
grapes
Note; The iterable created in the example above is [0, 1, 2, 3].
Using a While Loop: You can also loop through the list items by using a while loop.
Use the len() function to determine the length of the list, then start at 0 and loop your way
through the list items by refering to their indexes. Remember to increase the index by 1 after each iteration.
Example: Print all items, using a while loop to go through all the index numbers.
output will be
apple
banana
cherry
grapes
How to Loop Through A List Using List Comprehension?
List Comprehension offers the shortest syntax for looping through lists.
Example: A short hand for loop that will print all items in a list.
listA = ["apple", "banana", "cherry", "grapes"]
[print(x) for x in listA]
output will be
apple
banana
cherry
grapes
More About List Comprehension
List comprehension offers a shorter syntax when you want to create a new list based on the
values of an existing list.
For instane based on a list of fruits, you want a new list, containing only the fruits with the
letter "a" in the name. Without list comprehension you will have to write a for statement with a
conditional test inside.
But with list comprehension you can do all that with only one line of code.
Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
output will be
['apple', 'banana', 'mango']
Important to Remember
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has index [1] etc.
When we say that lists are ordered, it means that the items have a defined order, and that order
will not change. If you add new items to a list, the new items will be placed at the end of the list.
Changeable: The list is changeable, meaning that we can change, add, and remove items in a list after
it has been created.
Since lists are indexed, lists can have items with the same value i.e. lists Allow Duplicates.
Example
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
output will be
['apple', 'banana', 'cherry', 'apple', 'cherry']
Python Collections (Arrays): There are four collection data types in the Python programming language.
List is a collection which is ordered and changeable. Allows duplicate members.
Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate members.
Dictionary is a collection which is ordered** and changeable. No duplicate members.