[Python Cookbook] Iteration over a List in Python

For Loop

ls = [1, 2, 3, 4]
for i in ls:
    print (i)

 

Enumerate Method

ls = [1, 2, 3, 4]
for i, j in enumerate(ls):
    print(i, j)

Out:

  0 1

  1 2

  2 3

  3 4

List Comprehension

Syntax:

new_list = [expression(i) for i in old_list if filter(i)]

It's equivalent to

new_list = []
for i in old_list:
    if filter(i):
        new_list.append(expressions(i))

 

posted @ 2020-03-03 02:02  Sherrrry  阅读(135)  评论(0编辑  收藏  举报