How to Use List in Python


In this example we will show how to use list in Python.

Source Code

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# list operations
# create a list
testList = [110, 'Police', ['brave', 'strong', 'justice', 'love']]

# calculate the length of List
print('List length:', len(testList))

# output from second list elements to the end of the list.
print(testList[1:])

# add element to List
testList.append('firefighter')
print('\nList length:', len(testList))
print(testList[-1])

# Pop the first element
print(testList.pop(0))
print('\nList length:', len(testList))
print(testList)

# List merge, connect a list to the tail of another list.
testlist2 = ['Local office']
testList.extend(testlist2)
print('\nList length:', len(testList))
print(testList)

Output:

List length: 3
['Police', ['brave', 'strong', 'justice', 'love']]

List length: 4
firefighter
110

List length: 3
['Police', ['brave', 'strong', 'justice', 'love'], 'firefighter']

List length: 4
['Police', ['brave', 'strong', 'justice', 'love'], 'firefighter', 'Local office']
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments