List, Dictionary, Set and Generators Comprehensions in Python

    

   # List comprehension []
listc = [i for i in range(20)]
print(listc)
print([i for i in range(1, 21) if i%2!=0])

# Dictionary comprehension {}
mydict = {i:f"item{i}" for i in range(1, 6)}
print(mydict)

# Dictionary comprehension can also be used to reverse key, value pairs
newdict = {value:key for key, value in mydict.items()}
print(newdict)

# Set comprehension {}
setc = {i for i in [3,4,5,6,3,4,5,6]}
print(setc)

# Generator comprehension ()
genc = (i for i in range(5))
print(genc.__next__())
print(genc.__next__())
print(genc.__next__())
print(genc.__next__())
print(genc.__next__())
# or
for item in genc:
    print(item)

    

Comments

Popular posts from this blog

Quotation marks to wrap an element in HTML

What is the difference between iostream and iostream.h in cpp?

The Basic Structure of a Full-Stack Web App