220k views
1 vote
What does prices = list(values) do exactly. I am having a hard time understanding the book.

What does prices = list(values) do exactly. I am having a hard time understanding-example-1
User MazBeye
by
4.7k points

1 Answer

6 votes

Answer:

The difference between,

prices = values

prices = list(values):

In the first line, the variable prices is being assigned the value of the variable values. This means that prices and values will now refer to the same object in memory.

In the second line, the variable prices is being assigned a new value, which is a list version of the original values object. This creates a new object in memory, which is a list containing the same elements as the original values object. The original values object is not modified.

Step-by-step explanation:

Here's an example to illustrate the difference:

values = [1, 2, 3]

prices = values

print(prices) # Output: [1, 2, 3]

prices = list(values)

print(prices) # Output: [1, 2, 3]

In this example, values is initially set to a list containing the elements 1, 2, and 3. Then, the variable prices is assigned the value of values, so prices and values both refer to the same object in memory.

Next, the variable prices is assigned a new value, which is a list version of the original values object. This creates a new object in memory, which is a list containing the same elements as the original values object. The original values object is not modified.

As a result, when we print prices, we see the same list as when we print values. However, prices and values are now two separate objects in memory, even though they contain the same elements.