Can i ask a question


#1

here is a code block answer deemed correct:

numerical_list[len(numerical_list)-1]
thousand_or_greater = []
for people in numerical_list:
name = people[0]
pop = people[1]
if pop >= 1000:
thousand_or_greater.append(name)
print(thousand_or_greater[0:10])

what I’d like to know is.

Is the code beneath which I came up with more efficient than setting variables within the for loop. it prints out the same result I just want to know if its ok to do?

my code=

numerical_list[len(numerical_list)-1]
thousand_or_greater = []
for people in numerical_list:
if people[1] >= 1000:
thousand_or_greater.append(people[0])
print(thousand_or_greater[0:10])

thanks in advance :slight_smile:


#2

efficiency is a funny term, or rather its a complicated term. Efficiency can mean a lot of different, readability, maintainability (is it easy to change?) and so forth. Less lines of code doesn’t always mean its better


#3

I’m really new to Python, but sometimes I look at the answers and think ‘‘why can’t I just do it this way?’’. Obviously the more I grasp the better understanding I’ll get. It’s such a valuable asset to have people like yourself on here to talk about it with. :slight_smile:


#4

In the beginning its really difficult to distinguish between good and bad code. Guidance can certainly be useful.


#5

In terms of speed - you need to know what each thing you write does, and then you consider how much work that is to carry out (not very different from considering how much work it is to get an apple from the store)

For example, if two pieces of code both iterate over a list once, and that’s mostly all it does, then they’re more or less equally efficient and any further reasoning would require measurement (measuring is not the easiest thing to do right though and can easily be misleading. It’s also not many pieces of code that you’d care to measure, most things are “fast enough” and that’s all you care about)

On the other hand, some piece of code might search through the whole list each time it visits a value in the list. So it would do len(list) * len(list) amount of work. That might be bad depending on how long that list could be in the worst case.

As soon as something is reasonably efficient, it’s more important that the code is easily read - it should be ideally be possible to look at it and say that it’s obviously correct, or to look at individual pieces and say this about each piece, and then say the same thing about how the pieces are used together


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.