Learn Python Easy Way Part 4 (Lists)

Let us continue from where we left in the last article. We will see some more ways to work with lists in Python

Finding numbers of items in a list

mylist = ['Dehli', 'Washington', 'Tokyo']
len(mylist)
 3


mylistpair = [('India','Dehli'),('USA','Washington'),('Japan','Tokyo')]
len(mylistpair)
 3

Traversing through the items in a list

Let us look how to use the items inside a list with For loop

mynames = ["Sanjay", "Abhay", "Shailaja", "Vinay", "Ishaan"]
for name in mynames:
    print("Hello",name)

Hello Sanjay
Hello Abhay
Hello Shailaja
Hello Vinay
Hello Ishaan

mynumbers = [11, 22, 33, 44, 55, 66]
for num in mynumbers:
    print("Square of number", num, "is",num*num)

Square of number 11 is 121
Square of number 22 is 484
Square of number 33 is 1089
Square of number 44 is 1936
Square of number 55 is 3025
Square of number 66 is 4356


Using enumerate

mylist = ['Dehli', 'Washington', 'Tokyo', 'Mosco', 'London']
for index, name in enumerate(mylist):
    print("The city" , name , "is ", str(index) , " position in  the list")


The city Dehli is  0  position in  the list
The city Washington is  1  position in  the list
The city Tokyo is  2  position in  the list
The city Mosco is  3  position in  the list
The city London is  4  position in  the list