Today I had to do another assignment which is to create a python program which prints the elements of a list followed by their corresponding indices. Each element and its index must be on the same line seperated by a space. And if the list is empty, print “Empty List”.

I’m going to make a list called num and put 1 to 4 inside.

num = [1, 2, 3, 4]

Then I’ll use the if statement to do:

if len(num) == 0:
    print("Empty List")

So this will check if the list is empty first. But if it isn’t, I’ll use else to print out something which is the elements and index. After else, I’ll use for loop to print out the elements and index.

else:
    for i in range(len(num)):
        print(f"{num[i]} {i}")

Or:

else:
    for i in range(len(num)):
        print(num[i], i)

So putting them together, I’ll get:

Input:

num = [1, 2, 3, 4]
if len(num) == 0:
    print("Empty List")
else:
    for i in range(len(num)):
        print(f"{num[i]} {i}")

Or:

num = [1, 2, 3, 4]
if len(num) == 0:
    print("Empty List")
else:
    for i in range(len(num)):
        print(num[i], i)

Output:

1 0
2 1
3 2
4 3

Now I’m going to make an empty list and try see if it works.

Input:

emp = []
if len(num) == 0:
    print("Empty List")
else:
    for i in range(len(num)):
        print(num[i], i)

Output:

Empty List

And it works!

BONUS!!!

This time I’m going to use a funtion called enumerate(). But I won’t do the empty list thing.

for count, item in enumerate(num):
    print(f"{item} {count}")

And there you go. Byeeeeee! Be ready for my next post…

Reference: