Skip to main content
Practice

power-of-two-list

---
id: power-of-two-list
title: Creating a Power of Two List - Solution Guide
description: Write a Python function to generate a list containing powers of 2 up to a given integer n.
tags:
- Python
- List
- Exponentiation
sidebar_position: 9
isPublic: false
---

# Creating a Power of Two List - Solution Guide

Explore three different methods to generate a list of powers of 2.

<br />

```python title="Method 1"
def solution(n):
result = [] # Create an empty list
for i in range(n+1): # Iterate over numbers from 0 to n
result.append(2**i) # Append 2 to the power of i to the list
return result

Using the code above, you can create a list containing numbers that are powers of 2 based on the input integer n.


Example Use Case

Input/Output Example
n = 3

result = solution(n)
print(result) # Output: [1, 2, 4, 8]

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.