1

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])
1
  • 1
    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. Commented Feb 18, 2022 at 8:11

3 Answers 3

1

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'>
Sign up to request clarification or add additional context in comments.

8 Comments

What about the first result with a code like print([i[2] for i in lst]) ?
@mvp I'm sorry, I do not understand what you are asking. What would you like with the code print([i[2] for i in lst])? :-)
Just wondering if there was a way to get this output: 1, 2, 3, 4, 5, 6 and so on with one line of code :)
@mvp Added example. :-)
@mvp Added too. :-)
|
0

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

Comments

0
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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.