AI Basics with AK

Season 02 - Introduction to Python Programming

Arun Koundinya Parasa

Episode 09

LISTS OPERATIONS

List Operations

  • Append
  • Extend
  • Insert
  • Remove
  • Pop
  • Reverse
  • List Comprehenions

Append & Extend

my_list = []
my_list.append(1)
my_list.append(2)
my_list.append(3)
print(my_list)
[1, 2, 3]

As we know, a list is mutable in Python. We can add an element to the end of a list using the built-in append() function

[1]+2
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-40d7fb3750a9> in <cell line: 1>()
----> 1 [1]+2

TypeError: can only concatenate list (not "int") to list
[1] + [2]
[1, 2]

The extend() method in Python is handy for adding multiple elements to the end of a list. Let’s delve into its functionality by exploring its implementation

my_list = [1, 2, 3]
another_list = [4, 5, 6]
my_list.extend(another_list)
print(my_list)
[1, 2, 3, 4, 5, 6]
[1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]

Insert & Remove

The insert() method in Python allows us to add an element at a specific position within a list. Let’s explore its functionality through practical example

my_list = [1, 2, 3, 4, 5]
my_list.insert(2, 'a')
print(my_list)
[1, 2, 'a', 3, 4, 5]
my_list = [1, 2, 3, 4, 5]
my_list.insert(0, 'a')
print(my_list)
['a', 1, 2, 3, 4, 5]

The remove() method in Python facilitates the removal of a specific element from a list. Let’s delve into how this method works

my_list.remove('a')
print(my_list)
[1, 2, 3, 4, 5]
my_list.remove(1)
print(my_list)
[2, 3, 4, 5]

Pop, Reverse & List Comprehensions

In Python, pop() method provides a way to remove and return an element from a specific index in a list.

my_list = [1, 2, 3, 4, 5]
popped_element = my_list.pop()
print(my_list)
print(popped_element)
[1, 2, 3, 4]
5
my_list.pop()
4
my_list
[1, 2, 3]

The reverse() method in Python offers a way to reverse the order of elements in a list.

my_list = [1, 2, 3, 4, 5]
my_list.reverse()
my_list
[5, 4, 3, 2, 1]
my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90]
print(len(my_list))
print(min(my_list))
print(max(my_list))
9
10
90

List comprehensions in Python offer a concise and elegant way to create lists based on existing ones or other iterable objects

my_list = []
for i in range(5):
  my_list.append(i)

print(my_list)
[0, 1, 2, 3, 4]
my_list = [i for i in range(5)]
print(my_list)
[0, 1, 2, 3, 4]

Thank You

Open In Colab