0

So, in this example I understand how does it work:

# Create a list of numbers
user_entries = ["10", "19.1", "20"]

# Create an empty list to store the float numbers
float_numbers = []

# Iterate over the elements in the list
for number in user_entries:
  # Convert the element to float type and append it to the float_numbers list
  float_numbers.append(float(number))

# Calculate the sum of the numbers in the float_numbers list
print(sum(float_numbers))

But next code works same way, but I don't really understand how does it rewrite "behind scenes". In debugging I cannot see the movement of the second code.

user_entries = ['10', '19.1', '20']
user_entries = [float(item) for item in user_entries]
print(sum(user_entries))
  • 2
    But your second code is different to your first: The first creates `float_numbers` which you print (the sum of). The second overwrites `user_entries`. – quamrana Dec 23 '22 at 12:54
  • 1
    `[ACTION for ITEM in CONTAINER]` same as `for ITEM in CONTAINER: LIST.add(ACTION)` – azro Dec 23 '22 at 12:55
  • 2
    I'm not sure what you're asking: you assign a list of values to a variable (whether it already has assigned value doesn't matter). Are you unsure about how list comprehension works, assigning values to variables? – dm2 Dec 23 '22 at 12:57
  • 1
    Your list comprehension is essentially a generator which is invoked until exhausted, with each result value being appended to the list that is being created (*not* rewritten, since it is being created from scratch). But in your example, creating an actual list is pointless and memory-inefficient. Instead, just do `sum(float(item) for item in user_entries)`, or `sum(map(float, user_entries))`. This avoids the creation of a temporary list. – Tom Karzes Dec 23 '22 at 12:57
  • `import dis` and try `dis.dis("[float(item) for item in user_entries]")` – doctorlove Dec 23 '22 at 13:00

0 Answers0