简体   繁体   中英

How to give type to argument within function

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'

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]

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

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'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM