Python – List

By | 14/08/2019

In this post, we will see how to manage a List in Python.

CREATE

# Empty List
lst1 = []

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

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


INSERT

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)

list1 = [1,2,3,4]
print(list1)

# adding the value 100 at the position 2 => [1,2,100,3,4]
list1.insert(2, 100)
print(list1)


DELETE

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)

list1 = [1,2,3,4]
print(list1)

# take the last item in the list and delete it from the list
lastItem = list1.pop()
print(f"The item is {lastItem}")
print(list1)


UPDATE 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 SLICING

list1 = [1,2,3,4]
print(f"List1 =>{list1}")

# COPY
list2 = list1.copy()

list1.remove(3)

print(f"List1 => {list1}")
print(f"List2=> {list2}")


# SLICING: =>  Lst[ Initial : End : IndexJump ]
list3 = [1,2,3,4,5,6,7]

# from 1 to 3
print(list3[1:3])  # [2,3]

# from 0 to 5
print(list3[0:5])  # [1,2,3,4,5]

# all items steps 2
print(list3[::2])  # [1,3,5,7]

# all items steps 2
print(list3[1::2])  # [2,4,6]

# reverse list
print(list3[::-1])



Leave a Reply

Your email address will not be published. Required fields are marked *