Assignment 5
Table of Contents
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:
- first make a list in this case I called mine
num - Then we can use
for-loopbut we have to userange()andlen(and then your list name)+ if you want you can check list part 2 on how to use for-loop - 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
- 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