Last answered:

27 Jul 2020

Posted on:

18 Jul 2020

1

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)
Instructor
Posted on:

27 Jul 2020

0
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.
import time
start = time.time()
for a in m:
print (m[m.index(a)], end = " ")
end = time.time()
print(end - start)
and
start = time.time()

for k in range(len(m)):
print (m[k], end = " ")
end = time.time()
print(end - start)
Hope this helps.
Best,
Martin

Submit an answer