Create a list with for loop Python | Example code

Using the range function you can create a list with for loop in Python. Use Python For Loop, to iterate over each element of the range, and then append the item to the list.

Example code Create a list with for loop Python

Simple python example code.

list_1 = list()

for x in range(5):
    list_1.append(x)

print(list_1)

Output:

Another example using map() Objects

txns = [5, 20, 50, 40]
TAX_RATE = .08


def get_price_with_tax(txn):
    return txn * (1 + TAX_RATE)


final_prices = map(get_price_with_tax, txns)

print(list(final_prices))

Output: [5.4, 21.6, 54.0, 43.2]

One more example Using List Comprehensions

Simple one line code.

squares = [i * i for i in range(10)]
print(squares)

Output:

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Do comment if you have any doubts and suggestions on this Python list topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.