List and Array in Python
The List is one of the built-in data type in Python. The four collection data types are: list, tuple, set and dictionary.
List can store and mix any data type.
exemple:
list1 = ["mango", "peach", "cherry"]
list2 = [1, 3, 4, 8, 9]
list3 = [False, True, False, True]
# Mixed data type list
list4 = [True, -21, "melon"]
# print list4
print(list4)
# result : [True, -21, "melon"]
Access list items:
List items are indexed and you can access them by referring their index number:
list1 = ["apple", "pineapple", "melon", "peach", "lemon", "orange"]
# return list item at specified index (2):
print(list1[1])
# pineapple
print(list1[-1])
# orange
# return a sub-list with
# items from index x included
# to index y excluded (y - 1):
# positive index:
# ---------------
print(list1[2:4]) # interval [2;4[
# ['melon', 'peach']
print(list1[2:]) # interval [2;♾️[
# ['melon', 'peach', 'lemon', 'orange']
print(list1[:4]) # interval [x;4[
# ['apple', 'pineapple', 'melon', 'peach']
# negative index:
# ---------------
print(list1[-4:-2]) # interval [-4;-2[
# ['melon', 'peach']
print(list1[-4:]) # interval [-4:♾️[
# ['melon', 'peach', 'lemon', 'orange']
print(list1[:-2]) # interval [x:-2[
# ['apple', 'pineapple', 'melon', 'peach']
Change item value
Use the index number to change item value:
list1 = ["apple", "pineapple", "melon", "peach", "lemon", "orange"]
# replace index 1 item
list1[1] = "Raspberry"
print(list1)
# ["apple", "Raspberry", "melon", "peach", "lemon", "orange"]
Change a range of item values:
list1 = ["apple", "pineapple", "melon", "peach", "lemon", "orange"]
# replace from index 1 to index 3 items
list1[1:3] = ["Fig", "Pear"] # interval [1;3[
print(list1)
# ["apple", "Fig", "Pear", "peach", "lemon", "orange"]
If you insert more items than you replace: replace the items in the list that match the specified index range, then insert the remaining ones after the upper bound of the interval.
list1 = ["apple", "pineapple", "melon", "peach", "lemon", "orange"]
# replace from index 1 to index 2
list1[1:2] = ["Fig", "Pear"] # interval [1;2[
print(list1)
# ["apple", "pineapple", "melon", "peach", "lemon", "orange"]
If you insert less items than you replace: replace the items in the list that match the specified index range, then remove the remaining items in the list that match the specified index range.
list1 = ["apple", "pineapple", "melon", "peach", "lemon", "orange"]
# replace from index 1 to index 3
list1[1:3] = ["Lychee"] # interval [1;3[
print(list1)
# ["apple", "Lychee", "peach", "lemon", "orange"]
Add items to list.
Append items to the list:
list1 = ["apple", "pineapple", "melon", "peach", "lemon", "orange"]
# append item at the end of the list
list1.append('apricot')
print(list1)
# ["apple", "pineapple", "melon", "peach", "lemon", "orange", "apricot"]
Insert item at specific index in the list:
list1 = ["apple", "pineapple", "melon", "peach", "lemon", "orange"]
# insert item at specified index
list1.insert(2, 'Guava')
print(list1)
# ["apple", "pineapple", "Guava", "melon", "peach", "lemon", "orange"]
Extend list with elements from one list to another.
list1 = ["Papaya", "Lychee", "Pomegranate"]
list2 = ["Peach", "Grapefruit", "Mango"]
# add list2 items at the end of list1
list1.extend(list2)
print(list1)
# ["Papaya", "Lychee", "Pomegranate", "Peach", "Grapefruit", "Mango"]
Work with other iterables with collection data type :
list1 = ["Papaya", "Lychee", "Pomegranate"]
tuple1 = ("Peach", "Grapefruit", "Mango")
list1.extend(tuple1)
print(list1)
# ["Papaya", "Lychee", "Pomegranate", "Peach", "Grapefruit", "Mango"]
Remove items from a list.
Use remove() method to remove the first occurence of one specified item.
list1 = ["Papaya", "Lychee", "Pomegranate", "Lychee"]
list1.remove('Lychee')
print(list1)
# ["Papaya", "Pomegranate", "Lychee"]
Remove specified index
The pop() method removes the specified index.
list1 = ["Papaya", "Lychee", "Pomegranate"]
list1.pop(1)
print(list1)
# ["Papaya", "Pomegranate"]
if you don't specify index, pop() removes the last item.
list1 = ["Papaya", "Lychee", "Pomegranate"]
list1.pop()
print(list1)
# ["Papaya", "Lychee"]
The del keyword also removes the specified index:
list1 = ["Papaya", "Lychee", "Pomegranate"]
del list1[2]
print(list1)
# ["Papaya", "Lychee"]
The del keyworkd delete the entire list.
list1 = ["Papaya", "Lychee", "Pomegranate"]
del list1
# None
The clear() method empties the entire list wouthout deleting it.
list1 = ["Papaya", "Lychee", "Pomegranate"]
list1.clear()
print(list1)
# []
Loop through a list
Loop through list items by using for loop.
example: print every item one by one in the list.
list1 = ["pineapple", "melon", "peach", "lemon", "orange"]
for x in list1:
print(x)
# pineapple
# melon
# peach
# lemon
# orange
Loop with index numbers
Loop through a list by using range()
and len()
built-in functions.
example: the range()
function returns a sequence of numbers.
the len()
function returns the number of items in an object.
list1 = ["pineapple", "melon", "peach", "lemon", "orange"]
for i in range(len(list1))
print(list1[i])
# pineapple
# melon
# peach
# lemon
# orange
Iterate with while loop
Loop through a list by using a while loop.
example: Iterates over each list items with their index numbers (i).
list1 = ["pineapple", "melon", "peach", "lemon", "orange"]
i = 0
while i < len(list1):
print(list1[i])
i = i + 1
# pineapple
# melon
# peach
# lemon
# orange
Loop with List Comprehension
List Comprehension is a shorter syntax to iterate through a list.
example: Iterate over the list and print each item.
list1 = ["pineapple", "melon", "peach", "lemon", "orange"]
[print(x) for x in list1]
# pineapple
# melon
# peach
# lemon
# orange
You can also create a new list with List Comprehension.
example: without List comprehension, here is the longer syntax using regular for loop and if statement.
old_list = ["pineapple", "melon", "peach", "lemon", "orange"]
new_list = []
for x in old_list:
if 'o' in x:
new_list.append(x)
print(new_list)
# ['melon', 'lemon', 'orange']
example: Now with List Comprehension, here is the shorter syntax.
old_list = ["pineapple", "melon", "peach", "lemon", "orange"]
new_list = [x for x in old_list if 'o' in x]
print(new_list)
# ['melon', 'lemon', 'orange']
List Comprehension syntax:
new_list = [expression for item in iterable if condition == True]
The if statement is optional. return a new list without changing the previous one.
The iterable can be any iterable object, like a list, tuple, set etc.
The expression is the current item but also the function result.
So you can apply a method before the loop ends.
example: Change each string item to upper case in the new list.
my_tuple = ("pineapple", "melon", "peach", "lemon", "orange")
my_list = [x.upper() for x in my_tuple if 'o' in x]
print(my_list)
# ['MELON', 'LEMON', 'ORANGE']
Sorting List
List objects have a sort() method that sort the list alphanumerically, in ascending order by default.
example: Sort the list alphabetically.
my_list = ["pineapple", "melon", "peach", "lemon", "orange"]
my_list.sort()
print(my_list)
# ["lemon", "melon", "orange", "peach", "pineapple"]
example: Sort the list numerically.
my_list = [50, 20, 10, 30, 40]
my_list.sort()
print(my_list)
# [10, 20, 30, 40, 50]
If you want to sort items in descending order, use sort(reverse = True)
instead.
example: Sort list alphabetically in descending order.
my_list = ["lemon", "melon", "orange", "peach", "pineapple"]
my_list.sort(reverse = True)
print(my_list)
# ['pineapple', 'peach', 'orange', 'melon', 'lemon']
example: Sort list numerically in descending order.
my_list = [10, 20, 30, 40, 50]
my_list.sort(reverse = True)
print(my_list)
# [50, 40, 30, 20, 10]
If you want to customize your own function, use sort(key = my_func)
.
example: Invert number sign when sorting.
def my_func(n):
return -n
my_list = [10, 20, 30, 40, 50]
my_list.sort(key = my_func)
print(my_list)
# [50, 40, 30, 20, 10]
Sort method is case sensitive by default.
The upper case letters are sorted before lower case letters.
example:
my_list = ["lemon", "melon", "Orange", "peach", "Pineapple"]
my_list.sort()
print(my_list)
# ['Orange', 'Pineapple', 'lemon', 'melon', 'peach']
Use built-in functions str.lower
or str.upper
as key function to make sort method case insensitive.
example:
my_list = ["Orange", "peach", "Pineapple", "melon", "lemon"]
my_list.sort(key = str.lower)
print(my_list)
# ['lemon', 'melon', 'Orange', 'peach', 'Pineapple']
You can also use reverse()
to sort a list in the opposit order.
my_list = ["Orange", "peach", "Pineapple", "melon", "lemon"]
my_list.reverse()
print(my_list)
# ['lemon', 'melon', 'Pineapple', 'peach', 'Orange']
Copy a List
Python uses references by default to save memory and increase speed.
Allocation by reference should not be confused with copying a list. Python always uses references by default for objects.
example: Here is a variable assignment.
list1 = ['peach', 'lemon', 'coconut']
list2 = list1
list1[0] = 'apricot'
print(list2)
# ['apricot', 'lemon', 'coconut']
list2.clear()
print(list1)
# []
Use the copy()
method to create a new list object in memory.
NB: the objects inside the new list are still references of the objects
from the previous one.
example: Here, the copy()
method create a new list object in memory.
The clear()
method won't affect the other list.
list1 = ['peach', 'lemon', 'coconut']
list2 = list1.copy()
list1.clear()
print(list2)
# ['peach', 'lemon', 'coconut']
You can also use the list()
constructor and the slice operator [:]
to copy a new list object.
list1 = ['peach', 'lemon', 'coconut']
list2 = list(list1)
list2.append('cherry')
list3 = list1[:]
list3.remove('lemon')
print(list1)
# ['peach', 'lemon', 'coconut']
print(list2)
# ['peach', 'lemon', 'coconut', 'cherry']
print(list3)
# ['peach', 'coconut']
Join Two Lists
There are several ways to concatenate lists in Python.
You can use the +
operator.
example: concatenate both lists.
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list3 = list1 + list2
print(list3)
# [1, 2, 3, 'a', 'b', 'c']
You can also loop through one of the list and add the elements one by one to the other list.
example: add one element per for loop iteration.
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
for x in list1:
list2.append(x)
print(list2)
# ['a', 'b', 'c', 1, 2, 3]
Finally, You can use the extend()
method to add the elements from one list to another.
example: add the elements from list2
to list1
.
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
list1.extend(list2)
print(list1)
# [1, 2, 3, 'a', 'b', 'c']