-1

I'm doing a CodeAcademy activity where I zipped two lists together. I get different print results depending on the order they are placed.

names = ["Mohamed", "Sara", "Xia", "Paul", "Valentina", "Jide", "Aaron", "Emily", "Nikita", "Paul"]
insurance_costs = [13262.0, 4816.0, 6839.0, 5054.0, 14724.0, 5360.0, 7640.0, 6072.0, 2750.0, 12064.0]

medical_records = zip(insurance_costs, names)

print (list(medical_records))

num_medical_records = len(list(medical_records))

print(num_medical_records)

When I print I get the expected list, but the num_medical_records is 0? If I switch the order of my print statements, the result is an empty list, but printing num_medical_records gives me the correct number "11".

medical_records = zip(insurance_costs, names)

num_medical_records = len(list(medical_records))

print (list(medical_records))

print(num_medical_records)

Why is medical_records mutating? Greatly appreciate your insight!

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
  • 3
    You aren't mutating a list. You are mutating your `zip` object, which is an iterator, and you use `list(medical_records)`, which exhausts the iterator – juanpa.arrivillaga Nov 23 '20 at 18:08

3 Answers3

1

I believe zip returns an iterator. When you call list(medical_records), you exhaust the iterator. That's why calling len(list(medical_records)) gets no result because there's nothing to yield.

Source: https://docs.python.org/3.3/library/functions.html#zip

NanoBit
  • 196
  • 1
  • 10
0

You should first save the zip(insurance_costs, names) into a list, e.g.

zipped_list = list(zip(insurance_costs, names))

then perform other actions on the zipped_list variable, under which a list is stored. The zip creates an iterator only, which is exhausted by the first function run on it.

DanDayne
  • 154
  • 6
0

The zip function can only be iterated over only once.

You can do something like this:

names = ["Mohamed", "Sara", "Xia", "Paul", "Valentina", "Jide", "Aaron", "Emily", "Nikita", "Paul"]
insurance_costs = [13262.0, 4816.0, 6839.0, 5054.0, 14724.0, 5360.0, 7640.0, 6072.0, 2750.0, 12064.0]

medical_records = list(zip(insurance_costs, names))

print (medical_records)

num_medical_records = len(medical_records)

print(num_medical_records)
asd asd
  • 146
  • 8