'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 1:[1]
In the first case, you are doing multiple prints. In the second case you are building a list with all the data, then this said list is printed
Solution 2:[2]
lst = ["id1", "id2", "id3", "id4", "id5", "id6", "id7", "id8"]
# You are iterating over the list
for i in lst:
# prints 3rd character in each element (i)
print(i[2]) # be default this statement has newline at end
# To print with spaces try print(i[2], end=' ')
# here you are doing it using list comprehension so the output will be in a list
print([i[2] for i in lst])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Titouan L |
| Solution 2 | Nanthakumar J J |
