# Operations on the List Data Structure in Python

This post is lesson 23 of 54 in the subject Python Programming Language

In the article List data structure in Python, you have learned about List. This article will explore some operations on List data structure in Python.

## 1. Traverse each element in the List

### 1.1. Using for loop

``````my_list = [2, 'goc', 'hoc', 'it', 8, 1, 3, 5]
# Using for loop
for i in my_list:
print(i, end=' ')``````

#### Result

``2 goc hoc it 8 1 3 5``

### 1.2. Using for loop and index of List

``````my_list = [2, 'goc', 'hoc', 'it', 8, 1, 3, 5]
# getting length of my_list
length = len(my_list)

# Iterating the index
for i in range(length):
print(my_list[i], end=' ')``````

#### Result

``2 goc hoc it 8 1 3 5``

### 1.3. Using a while loop

``````my_list = [2, 'goc', 'hoc', 'it', 8, 1, 3, 5]
# getting length of my_list
length = len(my_list)
i = 0
# Iterating using while loop
while i < length:
print(my_list[i], end=' ')
i += 1``````

#### Result

``2 goc hoc it 8 1 3 5``

### 1.4. Using for loop and enumerate() function

Returns an object including all the index and value of corresponding elements in the List.

``````my_list = [2, 'goc', 'hoc', 'it', 8, 1, 3, 5]
# Using enumerate()
for i, val in enumerate(my_list):
print ('index ', i, " - value ", val, sep='')``````

#### Result

``````index 0 - value 2
index 1 - value goc
index 2 - value hoc
index 3 - value it
index 4 - value 8
index 5 - value 1
index 6 - value 3
index 7 - value 5``````

## 2. Creating a List with List Comprehension

List comprehension also provides a shorter syntax to create a new List based on the values of another List.

``````my_list = [2, 'goc', 'hoc', 'it', 8, 1, 3, 5]
#Creating new_my_list include items which are string in my_list
new_my_list = [x for x in my_list if type(x)==str]
print(new_my_list)``````

#### Result

``['goc', 'hoc', 'it']``

#### Syntax of List Comprehension

``new_my_list = [expression for item in iterable if condition == True]``

#### Example of expression in List Comprehension

Expression is the element being processed of the new List about to be created.

``````fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
# Set the values in newlist to upper case
newlist = [x.upper() for x in fruits]
print("newlist with upper case:", newlist)
# Set all values in newlist to 'hello'
newlist = ['hello' for x in fruits]
print("newlist with 'hello':", newlist)``````

#### Result

``````newlist with upper case: ['APPLE', 'BANANA', 'CHERRY', 'KIWI', 'MANGO']
newlist with 'hello': ['hello', 'hello', 'hello', 'hello', 'hello']``````

#### Example of iterable in List Comprehension

Iterable can be any iterable object like a list, tuple, set, etc. For example, we can use the function `range()` to create an iterable object.

``````fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
# Creating newlist with range()
newlist = [x for x in range(10)]
print("newlist in range(10):", newlist)
# Creating newlist accept only numbers lower than 5
newlist = [x for x in range(10) if x < 5]
print("newlist in range(10) with condition:", newlist)``````

#### Result

``````newlist in range(10): [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
newlist in range(10) with condition: [0, 1, 2, 3, 4]``````

#### Example of condition in List Comprehension

In List Comprehension, condition is optional, it can be present or not.

``````fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
#Condition with if
# newlist include items which arenot 'apple'
newlist = [x for x in fruits if x != "apple"]
print("newlist with condition:", newlist)
#Condition is optional, can be omitted
# No if statement
newlist = [x for x in fruits]
print("newlist with no condition:", newlist)``````

#### Result

``````newlist with condition: ['banana', 'cherry', 'kiwi', 'mango']
newlist with no condition: ['apple', 'banana', 'cherry', 'kiwi', 'mango']``````

## 3. Sorting Lists in Python

The List object has the `sort()` function to sort the string and number elements in the List in descending or ascending order. By default, the elements are sorted in ascending order. If the `reverse=True` argument is passed to the `sort()` function, it will be sorted in descending order. Example:

``````char_list = ["banana", "apple", "cherry", "mango", "kiwi"]
num_list = [100, 50, 65, 82, 23]
# Sort by default
char_list.sort()
num_list.sort()
print("char_list_after_default_sort:", char_list)
print("num_list_after_default_sort:", num_list)
# Sort by reverse = True
char_list.sort(reverse = True)
num_list.sort(reverse = True)
print("char_list_after_reverse_sort:", char_list)
print("num_list_after_reverse_sort:", num_list)``````

#### Result

``````char_list_after_default_sort: ['apple', 'banana', 'cherry', 'kiwi', 'mango']
num_list_after_default_sort: [23, 50, 65, 82, 100]
char_list_after_reverse_sort: ['mango', 'kiwi', 'cherry', 'banana', 'apple']
num_list_after_reverse_sort: [100, 82, 65, 50, 23]``````

## 4. Copying Lists in Python

We can use the `copy()` function or the `list()` function to copy a List. Example:

``````my_list = [2, 'goc', 'hoc', 'it', 8, 1, 3, 5]
# copy() function
my_list_1 = my_list.copy()
print("my_list_1:", my_list_1)
# list() function
my_list_2 = list(my_list)
print("my_list_2:", my_list_2)``````

#### Result

``````my_list_1: [2, 'goc', 'hoc', 'it', 8, 1, 3, 5]
my_list_2: [2, 'goc', 'hoc', 'it', 8, 1, 3, 5]``````

Note: We cannot use the assignment operator to copy 2 Lists like my_list_1 = my_list. Because my_list_1 only refers to the List that my_list refers to. If my_list_1 or my_list changes, it will also cause the other list to change.

Example:

``````my_list = [2, 'goc', 'hoc', 'it', 8, 1, 3, 5]
my_list_1 = my_list
# Change items in my_list_1
my_list_1[0] = 'hello all'
my_list_1[1] = '9999'
print("my_list changed after my_list_1 changed:", my_list)``````

#### Result

``my_list changed after my_list_1 changed: ['hello all', '9999', 'hoc', 'it', 8, 1, 3, 5]``

## 5. Joining Lists in Python

The simplest way to join 2 or more Lists is to use the + operator.

``````my_list_1 = ['goc', 'hoc', 'it']
my_list_2 = [2, 2, 5, 8]
my_list_3 = ['welcome', '99', 0, 1]
# Concatenate my_list_1, my_list_2, my_list_3
my_list = my_list_1 + my_list_2 + my_list_3
print("my_list:", my_list)``````

#### Result

``my_list: ['goc', 'hoc', 'it', 2, 2, 5, 8, 'welcome', '99', 0, 1]``

We can use the `append()` function to join 2 Lists with a for loop.

``````my_list_1 = ['goc', 'hoc', 'it']
my_list_2 = [2, 2, 5, 8]
# Concatenate my_list_1, my_list_2 with append() and for
for x in my_list_2:
my_list_1.append(x)
print("my_list_1:", my_list_1)``````

#### Result

``my_list_1: ['goc', 'hoc', 'it', 2, 2, 5, 8]``

We can also use the `extend()` function to join one List to the end of another List.

``````my_list_1 = ['goc', 'hoc', 'it']
my_list_2 = [2, 2, 5, 8]
# Concatenate my_list_1, my_list_2 with extend()
my_list_1.extend(my_list_2)
print("my_list_1:", my_list_1)``````

#### Result

``my_list_1: ['goc', 'hoc', 'it', 2, 2, 5, 8]``

## 6. List Methods in Python

Python supports many methods to make it easier to manipulate Lists. Some commonly used methods with Lists are described in the table below.

#### Example using List methods

``````my_list = [2, 'goc', 'hoc', 'it', 8, 1, 3, 5]

# Add 'welcome' to the end of my_list
my_list.append('welcome')
# Output: [2, 'goc', 'hoc', 'it', 8, 1, 3, 5, 'welcome']
print("Append my_list:", my_list)

my_list_extend = ['hello', 'John']
# Extend my_list by my_list_extend
my_list.extend(my_list_extend)
# Output: [2, 'goc', 'hoc', 'it', 8, 1, 3, 5, 'welcome', 'hello', 'John']
print("Extend my_list:", my_list)

# Insert an item to my_list
my_list.insert(1, 'gochocit.com')
# Output: [2, 'gochocit.com', 'goc', 'hoc', 'it', 8, 1, 3, 5, 'welcome', 'hello', 'John']
print("Insert my_list:", my_list)

# Remove items from my_list
my_list.remove(2)
my_list.remove(8)
my_list.remove(5)
my_list.remove('welcome')
# Output: ['gochocit.com', 'goc', 'hoc', 'it', 1, 3, 'hello', 'John']
print("Remove my_list:", my_list)

# Pop item by default from my_list
pop_item = my_list.pop()
# Output: John
print("pop item:", pop_item)
# Output: ['gochocit.com', 'goc', 'hoc', 'it', 1, 3, 'hello']
print("Pop my_list:", my_list)

# Pop item at index 3 from my_list
pop_item = my_list.pop(3)
# it
print("pop item:", pop_item)
# Output: ['gochocit.com', 'goc', 'hoc', 1, 3, 'hello']
print("Pop my_list:", my_list)

# Index item from my_list
index_item = my_list.index('hoc')
# Output: 2
print("Index item:", index_item)

# Count my_list
# Output: 1
print("Size of my_list:", my_list.count('gochocit.com'))

# Clear my_list
my_list.clear()
# Output: []
print("my_list:", my_list)``````

#### Result

``````Append my_list: [2, 'goc', 'hoc', 'it', 8, 1, 3, 5, 'welcome']
Extend my_list: [2, 'goc', 'hoc', 'it', 8, 1, 3, 5, 'welcome', 'hello', 'John']
Insert my_list: [2, 'gochocit.com', 'goc', 'hoc', 'it', 8, 1, 3, 5, 'welcome', 'hello', 'John']
Remove my_list: ['gochocit.com', 'goc', 'hoc', 'it', 1, 3, 'hello', 'John']
pop item: John
Pop my_list: ['gochocit.com', 'goc', 'hoc', 'it', 1, 3, 'hello']
pop item: it
Pop my_list: ['gochocit.com', 'goc', 'hoc', 1, 3, 'hello']
Index item: 2
Size of my_list: 1
my_list: []``````

You can refer to more List methods in Python at More on Lists.

5/5 - (1 vote)
Previous and next lesson in subject<< The list data structure in PythonThe Tuple Data Structure in Python >>
0 Shares