Python: How to Create List by Comprehension (Example Codes)

A list comprehension

List comprehensions generate list objects with the following syntax:

'''
[expression for item in iterable object]
or
[expression for item in iterable object if conditional judgment]
'''

example

l1 = [x for x in range(5)]
print(l1)       # [0, 1, 2, 3, 4]

l2 = [x*2 for x in range(1,5)]
print(l2)       # [2, 4, 6, 8]

l3 = [x*2 for x in range(1,100) if x % 5 == 0]
print(l3)       # [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190]

l4 = [x for x in "abcdefghij"]
print(l4)       # ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

l5 = [(row,col) for row in range(3) for col in range(1,4)]
print(l5)  # [(0, 1), (0, 2), (0, 3), (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3)]
for l6 in l5:
    print(l6)

2. Dictionary comprehension

Dictionary comprehension generates a dictionary object, the syntax is as follows:

'''
{key:value for expressions in iterable objects}
Dictionary derivatives can also add if and multiple for loops
'''

example

# Count the number of occurrences of each character in the string
text = "i love liangxiaoxin,i can fall in love liangxiaoxin all the time."
count_dict = {d : text.count(d) for d in text}
print(count_dict)   # {'i': 10, ' ': 10, 'l': 8, 'o': 4, 'v': 2, 'e': 4, 'a': 7, 'n': 6, 'g': 2, 'x': 4, ',': 1, 'c': 1, 'f': 1, 't': 2, 'h': 1, 'm': 1, '.': 1}

Three, set derivation

Set comprehension generates a set, which is similar to the syntax format of list comprehension. The syntax is as follows:

'''
{ expression for item in iterable object}
or
{expression for item in iterable object if condition}
'''

example

s = {x for x in range(100) if x % 7 == 0}
print(s)    # {0, 98, 35, 70, 7, 42, 77, 14, 49, 84, 21, 56, 91, 28, 63}

Fourth, the generator derivation

Tuples have no comprehensions. Tuple comprehensions generate a generator object.
An iterator can only be run once. The first iteration can get the data, and the second iteration will not display the data.

example

t1 = (x*2 for x in range(1,100) if x % 9 == 0)
print(t1)     # <generator object <genexpr> at 0x00000257B30D69E8>
print(list(t1))    # [18, 36, 54, 72, 90, 108, 126, 144, 162, 180, 198]
print(tuple(t1))   # ()

t2 = (x*2 for x in range(1,100) if x % 9 == 0)
for t in t2:
    print(t,end="\t")    # 18    36    54    72    90    108    126    144    162    180    198

Read More:

Leave a Reply

Your email address will not be published. Required fields are marked *