Python – List

By | 14/08/2019

In this post, we will see how to manage the List with Python.

CREATE A LIST

# Empty List
lst1 = []

# List
lst2 = [1,2,3,4,5]
lst3 = [1,'two',3,'four']

print(lst1)
print(lst2)
print(lst3)



INSERT OBJECTS

lst1 = []
lst2 = [1,2,3,4,5]
lst4 = []

lst1.append(100)
lst1.append(200)
lst1.append(300)

lst4.append(100)
lst4.append(200)
lst4.append(300)

print("lst1: ", lst1)
print("lst4: ", lst4)

lst1.append(lst2)
lst4.extend(lst2)

print("lst1 append lst2: ", lst1)
print("lst4 extend lst2: ", lst4)



DELETE OBJECTS

lst1 = [1,2,3,4,5]
lst2 = [6,7,8,9,10]
lst3 = [3,5,6,7,3]

# remove the object
print("lst2: ", lst2)
lst2.remove(7)
print("lst2 after remove 7: ",lst2)

# the method remove, delete the first object
print("lst3: ",lst3)
lst3.remove(3)
print("lst3 after remove 3: ",lst3)

# remove using the index
# index starts from 0
print("lst1: ", lst1)
del lst1[2]
print("lst1 after remove object with index 2: ", lst1)

# remove all 
print("lst2: ", lst2)
lst2 = []
print("lst2: ", lst2)



UPDATE OBJECT AND SORT

lst1 = [1,2,3,4,5]
lst2 = [6,2,1,9,7]
lst3 = [3,5,6,7,3]

print("lst1: ", lst1)
lst1[1] = 20
lst1[4] = 50
print("lst1 after update: ", lst1)

print("lst2: ", lst2)
// the sort method modifies the original list
lst2.sort()
print("lst2 sorted: ", lst2)

print("lst3: ", lst3)
// the sorted method doesn't modify the original list
// but, it will create another list
lst4 = sorted(lst3)
print("lst4: ", lst4)
print("lst3: ", lst3)



COPY AND READ A LIST

import copy

lst1 = [1,2,3,4,5]

print("lst1: ", lst1)
lst2 = copy.deepcopy(lst1)
print("lst2: ", lst2)
lst2[1]=20
lst2[4]=50
print("lst1: ", lst1)
print("lst2: ", lst2)

print("")
print("lst1:")
for i in range(0,len(lst1)):
    print(lst1[i])

print("")
print("lst2:")
for i in lst2:
    print(i)





Leave a Reply

Your email address will not be published.