1

I am trying to make a function that shortens lists to only 4 elements. However, I am unable to assign a type to the argument of the function, which I have called my_list.

I tried using type(), but that did not work.

Here is some code:

LL = [2,3,4,5,6,2,5,4]
print(len(LL))
def remove_last_elements(the_list):

    the_list.type(list) #Here it gives an error message that I will put below

    for i in range (len(the_list)-4):
        the_list=the_list.remove(the_list[len(the_list)-1])
remove_last_elements(LL)
print(LL)

It gives me this error message. If I use .type().

    remove_last_elements(LL)
  File "C:\Users\visha\OneDrive\Desktop\Arnav's Things\Coding\Python Programs (and side-products)\Balloons.py", line 5, in remove_last_elements
    the_list.type(list)
AttributeError: 'list' object has no attribute 'type'

Here is another segment of code without the .type() thing:

LL = [2,3,4,5,6,2,5,4]
print(len(LL))
def remove_last_elements(the_list):
    for i in range (len(the_list)-4):
        the_list=the_list.remove(the_list[len(the_list)-1])
remove_last_elements(LL)
print(LL)

Which gives the error message below:

  remove_last_elements(LL)
  File "C:\Users\visha\OneDrive\Desktop\Arnav's Things\Coding\Python Programs (and side-products)\Balloons.py", line 5, in remove_last_elements
    the_list=the_list.remove(the_list[len(the_list)-1])
AttributeError: 'NoneType' object has no attribute 'remove'
3
  • What are you trying to do exactly? Why do you need to give a type? Commented May 16, 2019 at 21:28
  • the_list.remove will modify it in-place, rather than returning a value, so the_list will become None Commented May 16, 2019 at 21:30
  • 1
    What about LL[:4] or LL[:-4] if you want to remove the last four elements? Commented May 16, 2019 at 21:32

3 Answers 3

3

I'm not sure what you're attempting to do by "assigning a type to the list". Lists by definition are of type list, which you can validate with type(the_list). I don't recommend making any programmatic decisions based on the result of this, though. Just assume everything is the correct type and crash if it isn't.

If in doubt as to whether a method exists on an object and to see which ones are, you can use dir():

>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__
', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash_
_', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul_
_', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmu
l__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append',
 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'
]
>>> "type" in dir(list)
False
>>>

Secondly, list.remove() is a function that operates in place and returns the value None. when you assign (essentially) the_list = None, on the next iteration calling (essentially) None.remove() raises the second exception you've encountered.

Resolving these two errors yields:

LL = [2,3,4,5,6,2,5,4]

def remove_last_elements(the_list):
    for i in range (len(the_list)-4):
        the_list.remove(the_list[len(the_list)-1])

remove_last_elements(LL)
print(LL)

Now, is this function even necessary? I would argue not, for a few reasons.

Firstly, it hardcodes the value 4 without informing the caller, making it almost useless for additional purposes. If I want to remove 5 elements, for example, I'm out of luck and have to write a new function. I would prefer if the shortening size was a parameter to this function so I could specify list shortening of arbitrary n values of my own choice.

Secondly, remove always removes the first occurrence of an item in the list. Your resulting list, [2, 3, 6, 2] is confusing in relation to the service the function name implies "remove last elements". As the user of your function, I'm surprised when two of the last 4 elements in my list are still there!

As a final remark, .remove is a very slow operation: for every item in the list, we have to walk up to the entire list to locate and remove it. This will have a serious performance impact on large lists.

I'd use Python's slice operator to perform list shortening efficiently, succinctly and predictably:

>>> LL = [2,3,4,5,6,2,5,4]
>>> LL[:-4] # remove and return up to the last 4
[2, 3, 4, 5]
>>> LL[-4:] # remove and return the last 4
[6, 2, 5, 4]

You can modify your program to use this as follows:

LL = [2,3,4,5,6,2,5,4]

LL = LL[:-4]
print(LL) # => [2, 3, 4, 5]
Sign up to request clarification or add additional context in comments.

Comments

2

Python is dynamically typed. You can't declare the type of a variable like in C or C++. A list is a collection of elements which can have different types. The same list can hold everything: strings, integer, floats, custom classes, etc.

This: the_list.type(list) just does not make any sense.

EDIT after comments

As said in the comment, It's worth to say that since python 3.5 support for type hint is provided. You can read more about it here and in the docs

4 Comments

Python is strongly typed. quora.com/…
@MasonCaiby Thanks for the link. I'll fix my answer
Thank you. I guess I will just have to change my approach.
@Carcigenicate I know, but as you said, it's just an hint. But may be worth to mark the point in the answer.
1
LL = [2,3,4,5,6,2,5,4]
print(len(LL))
def remove_last_elements(the_list):
    for i in range (len(the_list)-4):
        the_list=the_list.remove(the_list[len(the_list)-1])
remove_last_elements(LL)
print(LL)

you're resetting the_list to none, because the_list.remove acts in place, and returns none

try this:

LL = [2,3,4,5,6,2,5,4]
print(len(LL))
def remove_last_elements(the_list):
    for i in range (len(the_list)-4):
        the_list.remove(the_list[len(the_list)-1])
remove_last_elements(LL)
print(LL)

You cannot set the type of a Python object with .type(), you just use type(x) to get the type of object x is. If you want to change the type of something from, say, a set to a list you could use list(set('a', 'b'))

4 Comments

Thank you, this is really helpful, but I still think that your example of code will not work because it will say that you can't use .remove() for a NoneType object (the_list)
Okay, let me try again. When I tried it, it gave an error message.
WHOAH IT WORKED. Thank you again.
Yeah of course. I would agree with @ggorlen that indexing into your list is a better, and more pythonic way of handling your problem. I fixed the code you had because I thought it would be more informative than telling you to do it a different way.

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.