Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python for loop list of strings different output

Why is this codes output different?

lst = ["id1", "id2", "id3", "id4", "id5", "id6", "id7", "id8"]

for i in lst:
    print(i[2])
    
print([i[2] for i in lst])

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

First is an iteration, where you print every index 2 of every string. The second is a list comprehension, where you create a new list with the same data as above and prints the list.

First:

lst = ["id1", "id2", "id3", "id4", "id5", "id6", "id7", "id8"]

for i in lst:
    print(i[2])

Result:

1
2
3
4
5
6
7
8

Second:

print([i[2] for i in lst])

Result:

['1', '2', '3', '4', '5', '6', '7', '8']

If you want the first version to imitate the same result as the second out, simply create a list and append to it:

newlst = []

for i in lst:
    newlst.append(i[2])
print(newlst)

Result:

['1', '2', '3', '4', '5', '6', '7', '8']

If you want to print the list comprehension in one line, like the for loop, then use:

[print(i[2]) for i in lst]

Result:

1
2
3
4
5
6
7
8
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading