Python – A little bit about lists and operations with them

Python’s lists are powerful. Especially, if you come from the VBA world its like switching to a new car after years of using the old red Ikarus. Thus, I have decided to write a small article about them, just to be handy for me or for someone else, looking for a good place with references.

python-logo-master-v3-TM

What can you do with the Python lists?

The Python language enables you to do the following operations without including additional libraries:

  • Extend
  • Append
  • Insert
  • Remove
  • Clear
  • Index
  • Count
  • Sort
  • Reverse

How are the done? Pretty much, see the code and the output and you would get it. There is one thing to note – the function List.pop([i]) does two things – if it is assigned to a variable, it returns the popped variable and it removes it from the list. Sounds great, eh?

Check out the code:

#extend OR append
print("extend OR append:")
listA = [1,2,3,4,5]
listA.append([6,7])
listA.extend([8])
print(listA)
print("-"*20 + "\n")

#insert
print("insert:")
listA.insert(3,"VitoshAcademy.com")
listA.insert(len(listA),"VitoshAcademy.com")
print(listA)
print("-"*20+ "\n")

#remove
print("remove:")
listA.remove("VitoshAcademy.com")
print(listA)
iVariable = listA.pop()
iVariable2 = listA.pop(0)
print(iVariable)
print(iVariable2)
print(listA)
print("-"*20+ "\n")   

#clear
print("clear:")
listB = list(listA)
print(listB)
listB.clear()
print(listB)
print("-"*20+ "\n")     

#index and count
print("index:")
iVariable = listA.index(3)
print(iVariable)
iVariable = listA.count(3)
print(iVariable)
print("-"*20+ "\n")     

#sort and reverse
print("sort and reverse:")
listA.extend([10,100,1,15])
print(listA)
listA.pop(4)
listA.sort()
print(listA)
listA.reverse()
print(listA)
print("-"*20+ "\n")     

This is the output of the code:

[evaluate ListPython.py]
extend OR append:
[1, 2, 3, 4, 5, [6, 7], 8]
--------------------

insert:
[1, 2, 3, 'VitoshAcademy.com', 4, 5, [6, 7], 8, 'VitoshAcademy.com']
--------------------

remove:
[1, 2, 3, 4, 5, [6, 7], 8, 'VitoshAcademy.com']
VitoshAcademy.com
1
[2, 3, 4, 5, [6, 7], 8]
--------------------

clear:
[2, 3, 4, 5, [6, 7], 8]
[]
--------------------

index:
1
1
--------------------

sort and reverse:
[2, 3, 4, 5, [6, 7], 8, 10, 100, 1, 15]
[1, 2, 3, 4, 5, 8, 10, 15, 100]
[100, 15, 10, 8, 5, 4, 3, 2, 1]
--------------------

Enjoy it! 😀