Borislav Hadzhiev
Last updated: Apr 20, 2022
Photo from Unsplash
The Python "TypeError: list expected at most 1 argument, got 2" occurs when we
pass multiple arguments to the list()
class which takes at most 1 argument. To
solve the error, use the range()
class to create a range object or pass an
iterable to the list()
class.
Here is an example of how the error occurs.
# ⛔️ TypeError: list expected at most 1 argument, got 2 my_list = list(0, 5)
If you meant to create a range of integers, use the range()
class.
my_list = list(range(0, 5)) print(my_list) # 👉️ [0, 1, 2, 3, 4]
And if you meant to create a list containing multiple items, pass the items in
an iterable in the call to the list()
class.
my_list = list(['a', 'b', 'c']) print(my_list) # 👉️ ['a', 'b', 'c']
The list class takes an iterable and returns a list object.
The range class is
commonly used for looping a specific number of times in for
loops and takes
the following parameters:
Name | Description |
---|---|
start | An integer representing the start of the range (defaults to 0 ) |
stop | Go up to, but not including the provided integer |
step | Range will consist of every N numbers from start to stop (defaults to 1 ) |
If you only pass a single argument to the range()
constructor, it is
considered to be the value for the stop
parameter.
for n in range(5): print(n) result = list(range(5)) # 👇️ [0, 1, 2, 3, 4] print(result)
start
argument is omitted, it defaults to 0
and if the step
argument is omitted, it defaults to 1
.If values for the start
and stop
parameters are provided, the start
value
is inclusive, whereas the stop
value is exclusive.
result = list(range(1, 5)) # 👇️ [1, 2, 3, 4] print(result)
If the value for the stop
parameter is lower than the value for the start
parameter, the range will be empty.
result = list(range(1, 0)) # 👇️ [] print(result)