0

Can you help me optimize the code. This is in Python:

for fruit in fruit_list:
    fruit_id = uuid.uuid4()
    fruit_nos.append(TotalFruits(fruit_id, fruit))

(1) So there's a fruit list that contains a list of fruits

(2) For each fruit we generate a fruit_id using uuid

(3) We pass the fruit_id and the fruit to a class Total Fruits that returns the total number of fruits of that variety

(4) We append that to a fruit_nos list

I was trying to do list comprehensions but fruit_id = uuid.uuid4() is becoming a problem. So, I would do:

fruit_nos = [TotalFruits(fruit_id, fruit) for fruit in fruit_list]

But of course, I'll miss the uuid part. Is there an efficient way to the code?

2 Answers 2

1

You can generate the uuid within the comprehension:

fruit_nos = [TotalFruits(uuid.uuid4(), fruit) for fruit in fruit_list]

Note: uuid.uuid4() returns a UUID object. If you need a string - try using the hex attribute of that object: uuid.uuid4().hex

Sign up to request clarification or add additional context in comments.

Comments

0

You can include fruit_id = uuid.uuid4() inside the Class then you can use the list comp

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.