FAQ: Modules: Python - Modules Python Introduction

This community-built FAQ covers the “Modules Python Introduction” exercise from the lesson “Modules: Python”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Computer Science

FAQs on the exercise Modules Python Introduction

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

2 posts were split to a new topic: Why doesn’t datetime.now() match with the current time?

Hello Team PyThon,

I’m in the Intro to Modules lessons. I have a quick question on behavior of code. Why does PyThon behave differently with looping in comprehensive list vs. traditional format?

For Example,
for i in range(1, 101):
random_list = [random.randint(1, 100)]
continue
print(random_list )

The outputs/returns [7] or [33] etc. I’m looking for an list with a 100 random numbers in it.

Verses:
random_list = [random.randint(1, 101) for i in range(101)]

The above line of code returns:

[58, 13, 1, 30, 25, 25, 43, 21, 85, 95, 55, 63, 30, 98, 69, 90, 14, 24, 94, 55, 3, 60, 15, 32, 52, 1, 11, 1, 49, 2, 99, 99, 97, 85, 93, 98, 14, 2, 59, 5, 93, 58, 94, 83, 23, 57, 25, 63, 64, 5, 13, 11, 5, 90, 68, 22, 26, 6, 95, 73, 28, 17, 34, 79, 25, 40, 78, 8, 31, 2, 50, 56, 50, 90, 81, 88, 54, 31, 47, 19, 27, 23, 35, 79, 64, 6, 73, 14, 82, 49, 7, 92, 49, 83, 78, 36, 85, 51, 62, 40, 46]

Aren’t these two sets of code functionally equivalent? If so why do I get different output.

To preserve code formatting in forum posts, see: How do I format code in my posts?

For the list comprehension,

random_list = [random.randint(1, 101) for i in range(101)]
print(random_list)

the equivalent code would be:

random_list = []
for i in range(101):
    random_list.append(random.randint(1, 101))
print(random_list)

In your code snippet, in the body of your loop, you have the statement

random_list = [random.randint(1, 101)]

In each iteration of the loop, a list containing a single integer will be assigned to random_list. In the next iteration, the old list will be replaced/over-written by a new list (comprising of a single integer). You don’t want to discard the existing list in each iteration, rather you want to modify/append the existing list.

2 Likes

Mucho gracias mtrtmk!

1 Like