Python Creating List Elements Smartly
A List in Python is similar to an array. It is mutable, can store heterogeneous elements, and is easy to use. Now to add elements to an array you need to run a loop and then add elements one by one. Also If there are any conditionals involved then the size of the code increases. Python provides a more efficient way of doing it combining all the steps in a one-liner called List comprehension.
# the old way
list = []
for i in range(10):
list.append(i)
print(list)
# Output -> 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
# using list comprehension
list = [i for i in range(10)]
print(list)
# Output -> 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
# conditionals
list = [i**4 for i in range(1, 15) if i%3==0]
print(list)
# Output -> 81, 1296, 6561, 20736
list = [i**4 if i%5==0 else i/5 for i in range(1, 10)]
print(list)
# Output -> 0.2, 0.4, 0.6, 0.8, 625, 1.2, 1.4, 1.6, 1.8
If you have any questions about this code, you can drop a line in comment.
Comments
Post a Comment