Home > database >  Python for loop list of strings different output
Python for loop list of strings different output

Time:02-18

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

CodePudding user response:

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'>

CodePudding user response:

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

CodePudding user response:

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])
  • Related