Scripting >> Python >> Examples >> List >> How to manipulate Lists

#Initializing a List
L=[1,2,3,4]
M=["one","two","three","four","five"]

#Printing a List
print L

#Accessing a List item
L[0] returns 1

#Slicing

NewList = L[1:2]   returns [2,3]
NewList = L[2:]    returns [3,4]

#Length of a List
len(L) returns 4

# Sorting a List
sorted(L) returns [1,2,3,4]
sorted(M) returns["five","four","one","three","two"]

# Apend a List
L.append(5)  returns [1,2,3,4,5]

# Inserting a List
L.insert(0,0)  returns [0,1,2,3,4]

# Extending a List
N=L.extend(M)  returns[1,2,3,4,"one","two","three","four"]

# Delete an item from a List
del.L[0] returns [2,3,4]

# Pop the last item
L.pop() returns 4

# Pop indexed value from the List
L.pop(1) returns 2