Python — List

Minhazul Hasan Sohan
6 min readApr 6, 2021

List in Python is more likely an array in other programming languages. It is used to store multiple items in a single variable. So we can say that a list in python is a data structure that is an ordered sequence of elements and each element inside of a list is called an Item. Python list is mutable which means it’s changeable.

Declare a List:

In python programming, a list is declared by placing all the items (elements) inside square brackets [], separated by commas. We can put different types of datatype inside a list.

my_list = [] # empty list
my_list = [1, 2, 3] # list of integers
my_list = ['apple', 'banana', 'orange'] # list of strings
my_list = [3.4, "Bangladesh", [4, 5, 6]] # list with mixed datatypes

List Indexing:

List indexing is very much flexible in Python. We can use both positive and negative indexing in python.

>>> days = ['Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
>>> days[0]
'Saturday'
>>> days[2]
'Monday'
>>> days[6]
'Friday'
>>> days[-1]
'Friday'
>>> days[-2]
'Thursday'
>>> days[-7]
'Saturday'

List Slicing in Python:

In Python, list slicing is a common practice and it is the most used technique for programmers to solve efficient problems. With the colon(:) operator, we can specify where to start the slicing, where to end, and also specify the step. List slicing returns a new list from the existing list.

Syntax — List[Initial_Index, Ending_Index, Index_Jump]

>>> num = [10, 20, 30, 40, 50, 60, 70, 80, 90]
>>> num[:] # Returns all the elements
[10, 20, 30, 40, 50, 60, 70, 80, 90]
# Return the elements from index 2 to index (5-1)
>>> num[2:5]
[30, 40, 50]
# Return the elements from beginning to index (6-1)
>>> num[:6]
[10, 20, 30, 40, 50, 60]
# Return the elements from index 3 to end
>>> num[3:]
[40, 50, 60, 70, 80, 90]
# Return the elements from index -7 to index (-2-1)
>>> num[-7:-2]
[30, 40, 50, 60, 70]
# Return the elements from index -5 to end
>>> num[-5:]
[50, 60, 70, 80, 90]
# Return the elements from beginning to index (-2-1)
>>> num[:-2]
[10, 20, 30, 40, 50, 60, 70]
# Return every 2nd element of the list
>>> nums[::2]
[10, 30, 50, 70, 90]
>>> num[::-1]
[90, 80, 70, 60, 50, 40, 30, 20, 10]
>>> num[::-2]
[90, 70, 50, 30, 10]

Python List Methods:

append()

The append() method appends an element to the end of the list.

>>> fruits = ['apple', 'banana', 'cherry']
>>> fruits.append("orange")
>>> fruits
['apple', 'banana', 'cherry', 'orange']
>>> fruit2 = ['mango', 'goava']
>>> fruits.append(fruit2)
>>> fruits
['apple', 'banana', 'cherry', 'orange', ['mango', 'goava']]

insert()

The insert()method inserts an element at the specific index of a list.

>>> saarc = ['Afghanistan', 'Bhutan', 'India', 'Maldives', 'Pakistan', 'Sri-Lanka']>>> saarc.insert(1, 'Bangladesh')
>>> saarc
['Afghanistan', 'Bangladesh', 'Bhutan', 'India', 'Maldives', 'Pakistan', 'Sri-Lanka']
>>> saarc.insert(5, 'Nepal')
>>> saarc
['Afghanistan', 'Bangladesh', 'Bhutan', 'India', 'Maldives', 'Nepal', 'Pakistan', 'Sri-Lanka']

extend()

extend() method is used to append elements from another list / tuple to the current list. It is kind of list concatination.

>>> fruit1 = ["apple", "banana", "cherry"]
>>> fruit2 = ["mango", "pineapple", "papaya"]
>>> fruit1.extend(fruit2)
>>> fruit1
['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']
>>> numList = [1, 2, 3]
>>> numTuple = [4, 5, 6]
>>> numList.extend(numTuple)
>>> numList
[1, 2, 3, 4, 5, 6]

remove()

remove() method removes the specified item from a list. It takes the item as a parameter that we want to remove.

>>> fruit = ["mango", "pineapple", "papaya"]
>>> fruit.remove("pineapple")
>>> fruit
['mango', 'papaya']

pop()

pop() method also use to delete element. But instead of removing the specified item, it removes the specified index from a list. It takes the index number as a parameter that we want to remove. If we do not specify the index, then the pop() method removes the last item.

>>> fruit = ['apple', 'banana', 'mango', 'pineapple', 'papaya']>>> fruit.pop()
>>> fruit
['apple', 'banana', 'mango', 'pineapple']
>>> fruit.pop(2)
>>> fruit
['apple', 'banana', 'pineapple']

del

The del keyword also removes the specified index by taking index value. If we do not specify the index, then the del keyword delete the list completely. It means the variable does not exist the memory at all.

>>> fruit = ['apple', 'banana', 'mango', 'pineapple', 'papaya']>>> del fruit[3]
>>> fruit
['apple', 'banana', 'mango', 'papaya']
>>> del fruit
>>> fruit
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
fruit
NameError: name 'fruit' is not defined

clear()

clear() method empties the list. The list still exist but it has no contents.

>>> fruit = ['apple', 'banana', 'mango', 'pineapple', 'papaya']
>>> fruit.clear()
>>> fruit
[]

copy()

The copy() method copy all the list elements into a new list variable. Here both lists are independent and they contain different references. If we changes anythig to a list, that doesn’t effect the another list.

>>> a = [10, 20, 30, 40, 50, 60, 70]
>>> b = a.copy()
>>> b
[10, 20, 30, 40, 50, 60, 70]
>>> a
[10, 20, 30, 40, 50, 60, 70]
>>> b[2] = 25
>>> b
[10, 20, 25, 40, 50, 60, 70]
>>> a
[10, 20, 30, 40, 50, 60, 70]

So we can see that, changing of b does’t effect a anymore. But if we assign entire a list into the b list, then both variables will contain the same referance. So that, changing of any list will effects the another.

>>> a = [10, 20, 30, 40, 50, 60, 70]
>>> b = a
>>> a
[10, 20, 30, 40, 50, 60, 70]
>>> b
[10, 20, 30, 40, 50, 60, 70]
>>> b[2] = 25
>>> b
[10, 20, 25, 40, 50, 60, 70]
>>> a
[10, 20, 25, 40, 50, 60, 70]

count()

count() returns the number of elements with the specified value

>>> a = [10, 20, 30, 20, 50, 20, 70]
>>> x = a.count(20)
>>> x
3

index()

index() returns the index of the first element with the specified value.

>>> num = [4, 55, 64, 32, 16, 32]
>>> x = num.index(32)
>>> x
3

reverse()

reverse() method reverses the order of the list.

>>> digit = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> digit.reverse()
>>> digit
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

sort()

The sort() method sort the list alphanumerically, ascending, by default.

# Sort Alphabetically
>>> fruit = ["mango", "pineapple", 'apple', 'banana', "papaya"]
>>> fruit.sort()
>>> fruit
['apple', 'banana', 'mango', 'papaya', 'pineapple']
# Sort Numerically
>>> num = [15, 12, 18, 5, 1, 7]
>>> num.sort()
>>> num
[1, 5, 7, 12, 15, 18]

To sort descending, we can use the keyword argument reverse = True .

>>> fruit = ["mango", "pineapple", 'apple', 'banana', "papaya"]
>>> fruit.sort(reverse=True)
>>> fruit
['pineapple', 'papaya', 'mango', 'banana', 'apple']

We can also customize our own function by using the keyword argument key = function.

def myFunc(n):
return abs(n - 50)
num = [100, 50, 65, 82, 23]
num.sort(key=myFunc)
print(num)
Output: [50, 65, 23, 82, 100]

Loop Through a List

We can loop through a list items by using a for loop:

fruit = ["mango", "pineapple", 'apple', 'banana', "papaya"]
for x in fruit:
print(x)
Output:mango
pineapple
apple
banana
papaya

List Comprehension

List comprehension is an elegant way when we want to define and create lists based on existing lists. We can also does the same thing with a for statement with a conditional test inside but list comprehension makes that work more easier.

Without List Comprehension

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for item in fruits:
if "a" in item:
newlist.append(item)
print(newlist)
Output:
['apple', 'banana', 'mango']

With List Comprehension

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
Output:
['apple', 'banana', 'mango']

Another Example

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
first_col = [row[0] for row in matrix]
print(first_col)
Output:
[1, 4, 7]

--

--

Minhazul Hasan Sohan

চিত্ত যেথা ভয়শুন্য, উচ্চ যেথা শির