Printing out every object/ element in a list
Hello 365DS community!
I am about to finish the "Intro to Python" course, and I have a question after doing the "Use conditional statement and loops together exercise".
To print out every object in a list, which of the following code would be a "better" code?
m = [23, 45, 67, 89] (1) for a in m: print (m[m.index(a)], end = " ") (2): for k in range(len(m)): print (m[k], end = " ")
Really hoping for some sort of feedback! Thank you and happy learning everyone!
1 answers ( 0 marked as helpful)
Hi Min!
Thanks for reaching out!
It depends on what you are aiming to achieve.
If you are looking for a more organised and frequently encountered piece of code, perhaps you can opt for the second option.
But if you are trying to obtain the output quickly, it seems that the first option is the one to choose.
You can help yourself with the time module to measure the time it takes Python to deliver the output while executing the two code cells.
Best,
Martin
import time
start = time.time()
for a in m:
print (m[m.index(a)], end = " ")
end = time.time()and
print(end - start)
start = time.time()
for k in range(len(m)):
print (m[k], end = " ")
end = time.time()Hope this helps.
print(end - start)
Best,
Martin