Need help with coding a function in Python

Steve D'Aprano steve+python at pearwood.info
Mon Oct 31 20:40:48 EDT 2016


On Tue, 1 Nov 2016 09:09 am, devers.meetthebadger.jason at gmail.com wrote:

> http://imgur.com/a/rfGhK#iVLQKSW


Why on earth are you posting a screen shot?

Do you edit your code with Photoshop?

As soon as you post an unnecessary screenshot, you cut the number of people
willing and able to help you in half:

- anyone who is blind or visually impaired and reading this with a 
  screen reader cannot help you, even if they wanted to;

- anyone reading this post somewhere where access to imgur is blocked
  (say, from work);

- anyone who takes one look at the URL and says "F--k it, if they 
  can't be bothered to copy and paste text, I can't be bothered to
  follow the link".


We're volunteers. We're not paid to solve your problem, so if you make it
hard for us, we simply won't bother.


> How do I code a function that returns a list of the first n elements of
> the sequence defined in the link? I have no idea!!!!!

I have no idea either, because I cannot see the image. I'll leave you to
guess why I can't.

But the usual way to return a list of the first n elements of a sequence is
with slicing:

first_bunch = sequence[:n]  # a slice from index 0 to just before index n


If sequence is a list, then the slice sequence[:n] will also be a list.
Otherwise you may want to convert it to a list:

first_bunch = list(sequence[:n])

How does slicing work? You can think of it as a faster, more efficient way
of something like this:

def cut_slice(sequence, start=0, end=None):
    if end is None:
        end = len(sequence)
    result = []
    for i in range(start, end):
        value = sequence[i]
        result.append(value)
    return result


P.S. any time you think you want a while loop, 90% of the time you don't.
While-loops have their uses, but they're unusual. Whenever you know ahead
of time how many loops will be done, use a for-loop.

While-loops are only for those unusual cases where you don't know how many
times you need to loop.

Use a while-loop for:
- loop *until* something happens;
- loop *while* something happens;


Use a for-loop for:
- loop over each element of a sequence;
- loop a fixed number of times.




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list