Difference between a list comprehension and a for loop

前端 未结 5 2068
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-23 08:57
n=input()
y=n.split()
a=([int(x) for x in y])
print(a)

output

python .\\input_into_list.py
1 2 3
[1, 2, 3]

The above

5条回答
  •  我在风中等你
    2021-01-23 09:46

    The first example is what you call a list comprehension. It creates a list based on your values in a sequence and in this case your input y. List comprehensions are encouraged because of its simplicity and explicit purpose which returns you a list.

    a = [int(x) for x in y]
    

    Your second example is a for loop, loops, unlike the list comprehension, can be used for iterating through your sequence and perform multiple complex tasks. However, in your example variable a constantly gets updated with the latest value in y.

    for i in y:
        print(i)
        a = [i]
    

    To achieve the same result as a list comprehension:

    a = []
    for i in y:
        print(i)
        a.append(i)
    

    To keep it short, if you are planning to return a list, do it with a list comprehension when possible. For Python as for any language, there is no hard-and-fast rule, so use your discretion with keeping efficiency and readability in mind.

提交回复
热议问题