Thursday , December 2 2021
Home / Python / Python Lists
Built-in List Functions & Methods Basic List Operations & Updating Lists

Python Lists

Python List

Python Lists

Lists are used to store multiple items in a single variable. 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.

Lists are created using square brackets: []

In [1]:
L = []
print(L)
[]
In [2]:
L = [10,3.14,"Machine Learning",98.34,100,"Python",77]
print(L)
[10, 3.14, 'Machine Learning', 98.34, 100, 'Python', 77]
  • 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.
  • 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: Allow duplicates
In [3]:
print(L[0])
10

Determine the length and type of a list

In [4]:
print(len(L))
7
In [5]:
print(type(L))
<class 'list'>

Access list items

  • List items are indexed and you can access them by referring to the index number:
  • Negative indexing means start from the end.
    • 1 refers to the last item, -2 refers to the second last item etc.
  • You can specify a range of indexes by specifying where to start and where to end the range.
In [6]:
L = [10,3.14,"Machine Learning",98.34,100,"Python",77]
print(L)
print(L[:])
print(L[::])
print(L[0])
print(L[2:5])
print(L[2:])
print(L[:5])
print(L[-1])
print(L[-3:])
[10, 3.14, 'Machine Learning', 98.34, 100, 'Python', 77]
[10, 3.14, 'Machine Learning', 98.34, 100, 'Python', 77]
[10, 3.14, 'Machine Learning', 98.34, 100, 'Python', 77]
10
['Machine Learning', 98.34, 100]
['Machine Learning', 98.34, 100, 'Python', 77]
[10, 3.14, 'Machine Learning', 98.34, 100]
77
[100, 'Python', 77]

Change List Items

In [7]:
print(L)
[10, 3.14, 'Machine Learning', 98.34, 100, 'Python', 77]
In [8]:
L[0] = 89
print(L)
[89, 3.14, 'Machine Learning', 98.34, 100, 'Python', 77]

Change a Range of Item Values

In [9]:
print(L)
[89, 3.14, 'Machine Learning', 98.34, 100, 'Python', 77]
In [10]:
L[1:3] = ["Artificial Intelligence", "Deep Learning"]
print(L)
[89, 'Artificial Intelligence', 'Deep Learning', 98.34, 100, 'Python', 77]

Insert Items

  • To insert a new list item, without replacing any of the existing values, we can use the insert() method.
In [11]:
print(L)
[89, 'Artificial Intelligence', 'Deep Learning', 98.34, 100, 'Python', 77]
In [12]:
L.insert(2,"Machine Learning")
print(L)
[89, 'Artificial Intelligence', 'Machine Learning', 'Deep Learning', 98.34, 100, 'Python', 77]

Append Items

  • To add an item to the end of the list, use the append() method:
In [13]:
print(L)
[89, 'Artificial Intelligence', 'Machine Learning', 'Deep Learning', 98.34, 100, 'Python', 77]
In [14]:
L.append("Itronix")
print(L)
[89, 'Artificial Intelligence', 'Machine Learning', 'Deep Learning', 98.34, 100, 'Python', 77, 'Itronix']

Extent List

In [15]:
L1 = [10,46,67]
L2 = ["Apple","Mango","Kiwi"]
L1.extend(L2)
In [16]:
print(L1)
print(L2)
[10, 46, 67, 'Apple', 'Mango', 'Kiwi']
['Apple', 'Mango', 'Kiwi']

Remove Specified Item

In [17]:
print(L)
[89, 'Artificial Intelligence', 'Machine Learning', 'Deep Learning', 98.34, 100, 'Python', 77, 'Itronix']
In [18]:
L.remove('Python')
print(L)
[89, 'Artificial Intelligence', 'Machine Learning', 'Deep Learning', 98.34, 100, 77, 'Itronix']

Remove Specified Index

  • If you do not specify the index, the pop() method removes the last item.
In [19]:
print(L)
[89, 'Artificial Intelligence', 'Machine Learning', 'Deep Learning', 98.34, 100, 77, 'Itronix']
In [20]:
L.pop(2)
print(L)
[89, 'Artificial Intelligence', 'Deep Learning', 98.34, 100, 77, 'Itronix']

The del keyword also removes the specified index:

In [21]:
print(L)
[89, 'Artificial Intelligence', 'Deep Learning', 98.34, 100, 77, 'Itronix']
In [22]:
del L[4]
print(L)
[89, 'Artificial Intelligence', 'Deep Learning', 98.34, 77, 'Itronix']

The del keyword can also delete the list completely.

In [23]:
print(L)
[89, 'Artificial Intelligence', 'Deep Learning', 98.34, 77, 'Itronix']
In [24]:
del L
In [25]:
print(L)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-25-70501d4a5d78> in <module>
----> 1 print(L)

NameError: name 'L' is not defined

Clear the list

  • The clear() method empties the list.
In [26]:
L = [10,3.14,"Machine Learning",98.34,100,"Python",77]
L.clear()
In [27]:
print(L)
[]

Loop Through a List

  • You can loop through the list items by using a for loop:
In [28]:
L = [10,3.14,"Machine Learning",98.34,100,"Python",77]
for item in L:
    print(item)
10
3.14
Machine Learning
98.34
100
Python
77

Loop Through the Index Numbers

In [29]:
for i in range(len(L)):
    print(L[i])
10
3.14
Machine Learning
98.34
100
Python
77
In [30]:
L = [10,3.14,"Machine Learning",98.34,100,"Python",77]
i=0
while i < len(L):
    print(L[i])
    i = i + 1
10
3.14
Machine Learning
98.34
100
Python
77

Find Max and Min Number in List

In [31]:
L = [46,895,23,674,78,97]
print(max(L))
print(min(L))
895
23

Sort List Alphanumerically

In [32]:
L = ["orange", "mango", "kiwi", "apple", "papaya"]
L.sort()
print(L)
['apple', 'kiwi', 'mango', 'orange', 'papaya']
In [33]:
L = [45,9,90,53,23,89]
L.sort()
print(L)
[9, 23, 45, 53, 89, 90]

Sort Descending

In [34]:
L = [45,9,90,53,23,89]
L.sort(reverse=True)
print(L)
[90, 89, 53, 45, 23, 9]

By default the sort() method is case sensitive, resulting in all capital letters being sorted before lower case letters: According to ASCII Value

In [35]:
L = ["Orange", "mango", "Kiwi", "apple", "Papaya"]
L.sort()
print(L)
['Kiwi', 'Orange', 'Papaya', 'apple', 'mango']

So if you want a case-insensitive sort function, use str.lower as a key function:

In [36]:
L = ["Orange", "mango", "Kiwi", "apple", "Papaya"]
L.sort(key = str.lower)
print(L)
['apple', 'Kiwi', 'mango', 'Orange', 'Papaya']

Reverse Order

In [37]:
L = ["Orange", "mango", "Kiwi", "apple", "Papaya"]
L.reverse()
print(L)
['Papaya', 'apple', 'Kiwi', 'mango', 'Orange']

Python – List Comprehension

  • List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.
In [38]:
#store 1 to 10 numbers in a list
L = []
for i in range(1,11):
    L.append(i)
print(L)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

using list comprehension

  • newlist = [expression for item in iterable]
In [39]:
L = [i for i in range(1,11)]
print(L)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  • newlist = [expression for item in iterable if condition == True]
In [40]:
# store multiple of 3 from 1 to 100
L = [i for i in range(1,101) if i%3==0]
print(L)
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]
In [41]:
L = ["Apple","Mango","Kiwi"]
L1 = [x if x != "Mango" else "Orange" for x in L]
print(L1)
['Apple', 'Orange', 'Kiwi']

“Above is Return the item if it is not Mango, if it is Mango return Orange”.

Looping Using List Comprehension

In [42]:
L = [10,3.14,"Machine Learning",98.34,100,"Python",77]
[print(x) for x in L]
10
3.14
Machine Learning
98.34
100
Python
77
Out[42]:
[None, None, None, None, None, None, None]

Copy a List

You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and changes made in list1 will automatically also be made in list2.

There are ways to make a copy, one way is to use the built-in List method copy().

In [43]:
L1 = [1,2,3]
L2 = L1
print(L1)
print(L2)
[1, 2, 3]
[1, 2, 3]
In [44]:
L1[1] = 4
print(L1)
print(L2)
[1, 4, 3]
[1, 4, 3]
In [45]:
L1 = [1,2,3]
L2 = L1.copy()
print(L1)
print(L2)
[1, 2, 3]
[1, 2, 3]
In [46]:
L1[1] = 4
print(L1)
print(L2)
[1, 4, 3]
[1, 2, 3]

Another way to make a copy is to use the built-in method list().

In [47]:
L1 = [1,2,3]
L2 = list(L1)
print(L1)
print(L2)
[1, 2, 3]
[1, 2, 3]
In [48]:
L1[1] = 4
print(L1)
print(L2)
[1, 4, 3]
[1, 2, 3]

Join Two Lists

In [49]:
L1 = [1,2,3]
L2 = [4,5,6]
L3 = L1 + L2
print(L3)
[1, 2, 3, 4, 5, 6]

Another way to join two lists are by appending all the items from list2 into list1, one by one:

In [50]:
L1 = [1,2,3]
L2 = [4,5,6]
for item in L2:
    L1.append(item)
print(L1)
[1, 2, 3, 4, 5, 6]

Or you can use the extend() method, which purpose is to add elements from one list to another list:

In [51]:
L1 = [1,2,3]
L2 = [4,5,6]
L1.extend(L2)
print(L1)
[1, 2, 3, 4, 5, 6]

Count Item in a List

In [52]:
L = [10,20,30,10,40,50,10,60]
print(L.count(10))
3

Convert Tuple to list

In [53]:
T = (1,2,3,4,5,6)
print(T)

L = list(T)
print(L)
(1, 2, 3, 4, 5, 6)
[1, 2, 3, 4, 5, 6]

Remove duplicate items from list using set()

In [54]:
L = [1,2,3,1,4,6,4,5,6,8,6,7,8,9,1,5,6,3]
print(L)
[1, 2, 3, 1, 4, 6, 4, 5, 6, 8, 6, 7, 8, 9, 1, 5, 6, 3]
In [55]:
L1 = set(L)
print(L1)
{1, 2, 3, 4, 5, 6, 7, 8, 9}
In [56]:
L1 = list(L1)
print(L1)
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Multidimension List

In [57]:
L = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]] 
print(L) 
[[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]]
In [58]:
print(L[0])
print(L[1])
print(L[2])
[2, 4, 6, 8, 10]
[3, 6, 9, 12, 15]
[4, 8, 12, 16, 20]
In [59]:
print(L[0][0])
print(L[0][1])
print(L[0][2])
print(L[0][3])
print(L[0][4])
2
4
6
8
10

Iterate 2D List

In [60]:
L = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]] 
for row in L:
    print(row)
[2, 4, 6, 8, 10]
[3, 6, 9, 12, 15]
[4, 8, 12, 16, 20]
In [61]:
L = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]] 
for row in L:
    for col in row:
        print(col,end=' ')
    print()
2 4 6 8 10 
3 6 9 12 15 
4 8 12 16 20 

Create 1D Array

In [62]:
# First method to create a 1 D array
N = 5
arr = [0]*N
print(arr)
[0, 0, 0, 0, 0]
In [63]:
# Second method to create a 1 D array
N = 5
arr = [0 for i in range(N)]
print(arr)
[0, 0, 0, 0, 0]

Create 2D Array

In [64]:
# Using above first method to create a 2D array
rows, cols = (5, 5)
arr = [[0]*cols]*rows
print(arr)
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
In [65]:
# Using above second method to create a 2D array
rows, cols = (5, 5)
arr = [[0 for i in range(cols)] for j in range(rows)]
print(arr)
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
In [66]:
rows, cols = (5, 5)
arr=[]
for i in range(rows):
    col = []
    for j in range(cols):
        col.append(0)
    arr.append(col)
print(arr)
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

Adding a sublist using append method

In [67]:
a = [[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20]] 
a.append([5, 10, 15, 20, 25]) 
print(a) 
[[2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20], [5, 10, 15, 20, 25]]
In [68]:
a[0].extend([12, 14, 16, 18]) 
print(a)
[[2, 4, 6, 8, 10, 12, 14, 16, 18], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20], [5, 10, 15, 20, 25]]
In [69]:
a[2].reverse() 
print(a)
[[2, 4, 6, 8, 10, 12, 14, 16, 18], [3, 6, 9, 12, 15], [20, 16, 12, 8, 4], [5, 10, 15, 20, 25]]

About Machine Learning

Check Also

Python MySQL Insert Into Table

4 Python MySQL Insert Into Table Python MySQL Insert Into Table¶To fill a table in …

Leave a Reply

Your email address will not be published. Required fields are marked *