Issue
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
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
If you need a type string for the comprehension, you could do this:
s = "\n".join([i[2] for i in lst])
print(s)
print(type(s))
Result:
1
2
3
4
5
6
7
8
<class 'str'>
Answered By - user56700
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.