1. Introduction
In this example we will show how to manipulate lists with different methods in Python.
2. Tips
The difference between append and extend shall be clarified in comparison.
Source Code
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
a = [1, 3, 2]
b = [3, 4, 5]
print('Sort the first listn')
a.sort()
print(a)
print('nAdd the second listn')
print(a + b)
print('nAppend the second list')
a.append(b)
print(a)
print('nExtend the second list')
a.extend(b)
print(a)
Output:
Sort the first list
[1, 2, 3]
Add the second list
[1, 2, 3, 3, 4, 5]
Append the second list
[1, 2, 3, [3, 4, 5]]
Extend the second list
[1, 2, 3, [3, 4, 5], 3, 4, 5]
From the results above, we can see add and extend performs similarly, different from append function.