Python beginner (lists) - python

I need to write a function named make_ends that receives one parameter - a list. It returns a new list that contain the first and last items of the input list.
Here is my code, but it doesn't separate it into a list. I'm a little confused about how to go about this. Do I need to use the .join feature? If so, how do I do that? I think I am close.
def make_ends(x):
return x[0], x[-1]
Here was my earlier build, but it didn't do anything except return the original string:
def go_right(str):
if str >= 2:
a = str[-2:0] + str
return a
What was wrong with that?
Thanks for the help everyone.

You're actually very close; the only problem is that you're returning a tuple instead of a list. (Whatever a and b are, a, b is a tuple of those two things, just like [a, b] is a list of those two things.)
One way to solve this is to call list to make a list out of the tuple:
def make_ends(x):
return list((x[0], x[-1]))
But the easy way to do it is just to create a list in the first place:
def make_ends(x):
return [x[0], x[-1]]
You then ask another question:
Here was my earlier build, but it didn't do anything except return the original string:
def go_right(str):
if str >= 2:
a = str[-2:0] + str
return a
Let's go through this step by step.
First, str >= 2 is comparing a string to a number. In Python 2.x, either all strings are bigger than all numbers, or all strings are smaller than all numbers. (That's left up to the implementation.) So, this isn't a very useful check.
Maybe you wanted to check if len(str) >= 2 instead? But even then, I'm not sure what that would get you. If the length were 0 or 1, what would you want to do? As it is, you'd return None, which probably isn't right.
Meanwhile, str[-2:0] asks for all elements that come after 2-before-the-end, but before the start. There are no elements before the start, so this is empty. Then you add the original value to this empty collection, so you get the original value.
Also, as a side note, calling a parameter str is a bad idea. Besides the fact that it hides the built-in str (which is a function that turns anything into its string representation), it also strongly implies that what you're dealing with is a string, not a list.

Try the following
def make_ends(x):
return [x[0], x[-1]]
In the current form instead of a list you are creating a tuple. This is what the comma operator does when put between values

You're currently returning a tuple, not a list. Simply wrap it in square brackets to make it a list:
def make_ends(x):
return [x[0], x[-1]]
However, I'd question why you want a list in the first place. You know you're only returning two items, so you don't need it to be mutable - it seems to me perhaps that a tuple is what you want after all here.

There are indeed multiple ways of tackling this task
One would be the most common and probably most conventional
def make_ends(x):
return [x[0], x[-1]]
Another method
def make_ends(x):
finished = []
finished.append(x[0])
finished.append(x[1])
return finished
Also, you could turn the string into a list, allowing the function to work with strings
def make_ends(x):
x = list(x)
return [x[0], x[-1]]

you're very close. You just have to cast the return into a list.
return [x[0], x[-1]]

def make_ends(x):
return [x[0], x[-1]]

Related

This works BUT WHY?

I'm learing Python on codecademy and came across this solution for a function that's meant to remove duplicates from a list of numbers:
x = [1, 1, 2, 2]
def remove_duplicates(x):
p = []
for i in x:
if i != i:
p.append(i)
return i
I ran this in pycharm with some print statements and just got an empty list. I'm only curious because when I do this in my head, it makes no sense, but codecademy accepts this as an answer. Is it just a fluke? Or is this on a level I don't understand yet?
You are correct: it doesn't make any sense. First, it creates a list called p that gets each item that is not equal to itself. The only object that I know of that is not equal to itself is NaN, but you don't have any of those, so p is just an empty list. Defining p is useless, however, because it isn't even returned. What is returned is i, which is assigned to each item in the last, so it is the last item in the list by the end of the function. In short, that function is equivalent to this:
def remove_duplicates(x):
return x[-1]
I haven't heard what the function is supposed to return, but perhaps it is supposed to return the number of non-duplicate items. If it is, it "works" just because the last item in the list happens to be the number of non-duplicate items.
Take a look to this snippet to see the pythonic way to remove duplicated (good_result) and also to understand why your code doesn't make any sense:
x = [1, 1, 2, 2]
def remove_duplicates(x):
p = []
for i in x:
if i != i:
p.append(i)
return i
good_result = list(set(x))
print good_result
print remove_duplicates(x)
As you can see, your function is not returning the filtered list without duplicate values, it's just returning the last element of the list (index=-1). So codeacademy shouldn't accept that snippet as a valid answer to the question how to remove duplicateds from a list for sure.
Now, if we assume what codeacademy was really asking is for the number of unique values from a list, then is a casuality your broken code gives the right answer, which is the same as len(good_result). It worked just by luck just to say, it doesn't mean your code is correct :)
your code just returns the last element of the number, that is same as
return x[-1]
It doesn't return a list.
I think you need to check the question that they may be asking like,
a)function to return one of the duplicating element in a list.
b)function to return the no of duplicating elements in a list.
for the above two questions your answer is 2, by luck the answer is correct.

writing a function that return the reversed number

I am trying to write a Python function that get a number as input and returns its reversed number as output. for example: 1234 returns 4321.
this is what I try, but it return only ''
def reverse(num):
L=[]
x=str(num)
L1=list(x)
for i in L1:
L.insert(0,i)
print 'the reversed num is:'
x=''
for i in L:
x.join(i)
return x
any ideas?
def reverse(num):
return str(num)[::-1]
or one line:
lambda x: str(x)[::-1]
Well, the easy solution is this one:
>>> int(str(1234)[::-1])
4321
Your code can be fixed by changing the part
for i in L:
x.join(i)
return x
to
for i in L:
x += i
return x
Alternatively, just replace that section by
return ''.join(L)
What was wrong with your code? Because of wrong indentation, you returned in the first iteration of the for loop. You never assigned a name to x.join(i) so the return value was lost. What you expected join to do I do not know.
First, there is an easier way by converting to string, slicing the string and converting it back to a number.
def reverse(num):
return int(str(num)[::-1])
Second, there are multiple errors in your code:
1) your return statement is in the loop, so it will return after the first iteration;
2) x does not change because x.join() creates a new string and does not modify the string x (which is immutable by the way)
3) no need to convert the string into a list since you can directly iterate over the string (for i in x: ...)
4) join() takes an iterator as an argument. No need for the second loop: return ''.join(L)
thank you all for the helpful ideas.
here is my solution:
def reverse(n):
reverse=0
while(n>0):
dig=n%10
reverse=reverse*10
reverse=reverse+dig
n=n/10
return reverse
def reverse(num)
return str(num)[::-1]
Reverse a string in Python
Other users already gave good answers. Here is a different one, for study purposes.
num = 1234
print "".join(reversed(str(num)))
# 4321
You can convert to int afterwards.

How to remove and return element in python list

In python you can do list.pop(i) which removes and returns the element in index i, but is there a built in function like list.remove(e) where it removes and returns the first element equal to e?
Thanks
I mean, there is list.remove, yes.
>>> x = [1,2,3]
>>> x.remove(1)
>>> x
[2, 3]
I don't know why you need it to return the removed element, though. You've already passed it to list.remove, so you know what it is... I guess if you've overloaded __eq__ on the objects in the list so that it doesn't actually correspond to some reasonable notion of equality, you could have problems. But don't do that, because that would be terrible.
If you have done that terrible thing, it's not difficult to roll your own function that does this:
def remove_and_return(lst, item):
return lst.pop(lst.index(item))
Is there a builtin? No. Probably because if you already know the element you want to remove, then why bother returning it?1
The best you can do is get the index, and then pop it. Ultimately, this isn't such a big deal -- Chaining 2 O(n) algorithms is still O(n), so you still scale roughly the same ...
def extract(lst, item):
idx = lst.index(item)
return lst.pop(idx)
1Sure, there are pathological cases where the item returned might not be the item you already know... but they aren't important enough to warrant a new method which takes only 3 lines to write yourself :-)
Strictly speaking, you would need something like:
def remove(lst, e):
i = lst.index(e)
# error if e not in lst
a = lst[i]
lst.pop(i)
return a
Which would make sense only if e == a is true, but e is a is false, and you really need a instead of e.
In most case, though, I would say that this suggest something suspicious in your code.
A short version would be :
a = lst.pop(lst.index(e))

Python: Passing a list through a recursive function call causes the list to become 'NoneType', why?

I have the following recursive function:
def recurse(y,n):
if len(y) == n:
return y
else:
return recurse(y.append(1),n)
When I run it:
x=recurse([],10)
I get the following error:
TypeError: object of type 'NoneType' has no len()
It seems that the function gets past the if statement the 1st time around, then it goes into the next level of recursion, and there, y.append(1) is 'NoneType', why is it not: '[1]' as expected? I have thought about this for a while and I can't seem to figure it out. Any insight is appreciated!
The problem is here:
y.append(1)
The append() method returns None, so you can't pass its result for building the output list (you'd have to first append to the list and then pass it, as shown in other answers). Try this instead:
def recurse(y, n):
if len(y) == n:
return y
else:
return recurse(y + [1], n)
The above solution is more in line with a functional programming style. Using append adds an element to an existing list - which will mutate a function parameter, in general not a very good idea. On the other hand y + [1] creates a new list each time, leaving the parameter untouched. Proponents of functional programming will tell you that's a Good Thing.
list.append() calls the append method on a list, and while it modifies the list, it returns None.
So it does not return the list.
You want something like:
def recurse(y,n):
if len(y) == n:
return y
else:
y.append(1)
return recurse(y,n) # explicitly pass the list itself
y.append operates on y in place and returns None

What happens when returning a reversed list like this

I used this code to return a list say [1,2,3,4]
return (list.reverse())
But it simply wont return the correct result. I had to use
list.reverse()
return list
why is this happening? and when I break up my issue and do
list1 = list.reverse()
in console and print list1, it simply prints "list1"
p.s:- I am a beginner and still learning python.
list.reverse method doesn't return anything. It works over the elements on the list to which is applied (modifying the list). Hence, returning its result will return None. Here's the prof:
>>>[].reverse() == None
True
If you're trying to return a new list with element in reverse order, this is how you do it:
return list[::-1]
This is called slicing in Python and it's used to work with collections.
A small note about returning none: These methods don't actually return None. They don't return any value. But the result of evaluating a function that doesn't return any values is actually None in Python.
Hope this helps!
It's because list.reverse() method reverses list in-place - it doesn't return the reversed list. See the docs.
Use reversed:
return reversed(list)
Generally if you're returning the list reversed, the faster solution is
list.reverse()
return list
You could do
return reversed(list)
but that's generally slower and uses more memory, because it needs to create a new object.
The reason list.reverse() doesn't return the object for convenience is to remind you that it modifies the original list.

Categories

Resources