Solve - TypeError: set expected at most 1 argument, got 2

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

Solve - TypeError: set expected at most 1 argument, got 2 #

The Python "TypeError: set expected at most 1 argument, got 2" occurs when we pass multiple arguments to the set() class. To solve the error, pass an iterable containing the arguments to the set class, e.g. set([1,2]).

typeerror set expected at most 1 argument got 2

Here is an example of how the error occurs.

main.py
# ⛔️ TypeError: set expected at most 1 argument, got 2 my_set = set(1, 2)

The set class takes an iterable as an optional argument and returns a new set object.

main.py
my_set = set([1, 2]) my_set.add(3) print(my_set) # 👉️ {1, 2, 3} print(2 in my_set) # 👉️ True

Set objects are an unordered collection of unique elements.

Notice that we passed a list (an iterable) containing multiple values to create the set.

Alternatively, you can create a set by specifying multiple, comma-separated values between curly braces.

main.py
my_set = {1, 2} my_set.add(3) print(my_set) # 👉️ {1, 2, 3} print(2 in my_set) # 👉️ True

Note that set objects are an unordered collection of unique elements, so if you need to store the same value multiple times, or need to access an item in the collection by its specific index, you should use a list.

main.py
my_list = ['a', 'b', 'c'] print(my_list) # 👉️ ['a', 'b', 'c'] my_list.append('d') print(my_list) # 👉️ ['a', 'b', 'c', 'd'] my_list.insert(0, 'z') print(my_list) # 👉️ ['z', 'a', 'b', 'c', 'd'] print(my_list[0]) # 👉 'z'

Note that lists are created using square brackets.

The list.append() method adds an item to the end of the list.

The method returns None as it mutates the original list.

If you need to add an item at a specific index, use the insert() method.

The list.insert method inserts an item at a given position.

The method takes the following 2 parameters:

NameDescription
indexThe index of the element before which to insert
itemThe item to be inserted at the given index
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.