The 365 Data Science team is proud to invite you to our own community forum. A very well built system to support your queries, questions and give the chance to show your knowledge and help others in their path of becoming Data Science specialists.
Ask
Anybody can ask a question
Answer
Anybody can answer
Vote
The best answers are voted up and moderated by our team

Printing out every object/ element in a list

Printing out every object/ element in a list

1
Vote
1
Answer

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 Answer

365 Team
0
Votes

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

×
LAST CHANCE
Ready to Learn Data Science?
50% OFF