Skip to main content
  1. Posts/

Assignment 5

·239 words·2 mins

So today I am going to show you how to print the element and it’s index. So here’s my plan

For-loop way #

Plan:

  1. first make a list in this case I called mine num
  2. Then we can use for-loop but we have to use range() and len(and then your list name) + if you want you can check list part 2 on how to use for-loop
  3. but since we know that we can print the element we also want to print the index beside it so we do num[n], n
  4. Then the last thing you do is you use if we want to use it just in case the creator prints a empty list the program won’t run so this is how you do it
if len(num) == 0:
     print("The list is empty")
else:    
    for n in range(len(num)):
        print(num[n], n)

So the final plan would look like this:

num = [1, 2, 3, 4]

if len(num) == 0:
     print("The list is empty")
else:    
    for n in range(len(num)):
        print(num[n], n)

Bonus: Using enumerate() #

So this time instead of using for-loop we are going to use enumerate() so basically enumerate function take a takes a collection like a tuple or list and turns it into a enumerate function

for d, y in enumerate(num):
    print(d, y)

And that’s all. If you go here it will explain enumerate a bit more and range too it’s a good website

References: #