Ben Taylor
Ben Taylor

Reputation: 25

Cannot get 1st and 2nd element of a list

I'm trying to write a function definition that takes a sequence and returns the first and second values. I suspect my code is wrong because it can't take in a list, but I'm not sure. Here's my goal:

Write a function definition named first_and_second that takes in sequence and returns the first and second value of that sequence as a list.

Here's the code I'm having trouble with:

def first_and_second(list):
  return list[0 and 1]

Here's the test of whether I got it right:

assert first_and_second([1, 2, 3, 4]) == [1, 2]
assert first_and_second(["python", "is", "awesome"]) == ["python", "is"]

Upvotes: 0

Views: 1468

Answers (3)

Oblomov
Oblomov

Reputation: 9635

For a more concise solution, you can use lambda notation:

first_and_second = lambda l : l[:2]

It requires only one keyword instead of two and may therefore be considered a more pythonic way of doing simple things like this.

Since the lambda statement above actually is a function defition, you can just use it as follows:

assert first_and_second([1, 2, 3, 4]) == [1, 2]
assert first_and_second(["python", "is", "awesome"]) == ["python", "is"]

Upvotes: 0

Gino Mempin
Gino Mempin

Reputation: 29635

There's nothing wrong with how your function "takes in a list", but there's something wrong with how you use the passed list.

return list[0 and 1]

The expression 0 and 1 evaluates to 0:

>>> 0 and 1
0

So that code effectively becomes:

return list[0]

which will only return the 1st element. What you want to do is called slicing, which means getting a subset of a list. From this SO post on Understanding slice notation:

a[start:stop]  # items start through stop-1
a[start:]      # items start through the rest of the array
a[:stop]       # items from the beginning through stop-1
a[:]           # a copy of the whole array

The correct code is:

def first_and_second(aList):
  return aList[0:2]

which means "get the elements of aList from the index=0 element (the first value) up to the index=1 element (the second value)".

>>> def first_and_second(list):
...   return list[0:2]
>>> print( first_and_second([1, 2, 3, 4]) == [1, 2] )
True
>>> print( first_and_second(["python", "is", "awesome"]) == ["python", "is"] )
True

Also, note that I changed the function parameter list to aList. DO NOT name your parameters/variables as list because that is a built-in type in Python.

Upvotes: 1

DarkLeader
DarkLeader

Reputation: 589

def first_and_second(list):
    return [list[0],list[1]]

or

def first_and_second(list):
    return list[0:2]

Upvotes: 0

Related Questions