How do you initialize a list and add random values to it?
💡 Model Answer
To initialize an empty list in Python, simply use square brackets: my_list = []. To add random values, import the random module and use functions like random.randint(a, b) for integers or random.uniform(a, b) for floats. You can add a single value with my_list.append(value) or generate multiple values in a loop or comprehension. For example, to create a list of 10 random integers between 1 and 100:
import random
my_list = [random.randint(1, 100) for _ in range(10)]If you need to add values one by one, you can do:
for _ in range(10):
my_list.append(random.randint(1, 100))This approach is O(n) time and O(n) space, where n is the number of elements added. Using list comprehensions is generally more concise and slightly faster due to internal optimizations.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers — invisible to screen sharing.
Get Assisting AI — Starts at ₹500