python set constructor syntax

  • Last Update :
  • Techknowledgy :

Last Updated : 10 Aug, 2021,GATE CS 2021 Syllabus

1._
def __init__(self):
   # body of the constructor

Output : 

GeekforGeeks

Suggestion : 2

set() takes a single optional parameter:,Recommended Reading: Python sets,Note: We cannot create empty sets using { } syntax as it creates an empty dictionary. To create an empty set, we use set().,iterable (optional) - a sequence (string, tuple, etc.) or collection (set, dictionary, etc.) or an iterator object to be converted into a set.

Example

list_numbers = [1, 2, 3, 4, 2, 5]

# create set from list
numbers_set = set(list_numbers)
print(numbers_set)

# Output: {
   1,
   2,
   3,
   4,
   5
}

Example

list_numbers = [1, 2, 3, 4, 2, 5]

# create set from list
numbers_set = set(list_numbers)
print(numbers_set)

# Output: {
   1,
   2,
   3,
   4,
   5
}

The syntax of set() is:

set(iterable)

Example 1: Create sets from string, tuple, list, and range

# empty set
print(set())

# from string
print(set('Python'))

# from tuple
print(set(('a', 'e', 'i', 'o', 'u')))

# from list
print(set(['a', 'e', 'i', 'o', 'u']))

# from range
print(set(range(5)))

Example 2: Create sets from another set, dictionary and frozen set

# from set
print(set({
   'a',
   'e',
   'i',
   'o',
   'u'
}))

# from dictionary
print(set({
   'a': 1,
   'e': 2,
   'i': 3,
   'o': 4,
   'u': 5
}))

# from frozen set
frozen_set = frozenset(('a', 'e', 'i', 'o', 'u'))
print(set(frozen_set))

Example 3: Create set() for a custom iterable object

class PrintNumber:
   def __init__(self, max):
   self.max = max

def __iter__(self):
   self.num = 0
return self

def __next__(self):
   if (self.num >= self.max):
      raise StopIteration
self.num += 1
return self.num

# print_num is an iterable
print_num = PrintNumber(5)

# creating a set
print(set(print_num))

Suggestion : 3

The set() is a constructor method that returns an object of the set class from the specified iterable and its elements. A set object is an unordered collection of distinct hashable objects. It cannot contain duplicate values. ,The following example converts different iterable types into a set with distinct elements.,iterable: (Optional) An iterable such as string, list, set, dict, tuple or custom iterable class., TutorialsTeacher.com is optimized for learning web technologies step by step. Examples might be simplified to improve reading and basic understanding. While using this site, you agree to have read and accepted our terms of use and privacy policy.

Syntax:

set(iterable)
2._
numbers_list = [1, 2, 3, 4, 5, 5, 3, 2]
print("Converting list into set: ", set(numbers_list))

numbers_tuple = (1, 2, 3, 4, 5, 5, 4, 3)
print("Converting tuple into set: ", set(numbers_tuple))

numbers_dict = {
   1: 'one',
   2: 'two',
   3: 'three'
}
print("Converting dictionary into set: ", set(numbers_dict))

mystr = 'Hello World'
print("Converting string into set: ", set(numbers_string))
3._
Converting list into set: {
   1,
   2,
   3,
   4,
   5
}
Converting tuple into set: {
   1,
   2,
   3,
   4,
   5
}
Converting dictionary into set: {
   1,
   2,
   3
}
Converting string into set: {
   'H',
   'o',
   'W',
   'd',
   ' ',
   'l',
   'e',
   'r'
}
numbers_list = [1, 2, 3, 4, 5, 5, 3, 2]
print("Converting list into set: ", set(numbers_list))

numbers_tuple = (1, 2, 3, 4, 5, 5, 4, 3)
print("Converting tuple into set: ", set(numbers_tuple))

numbers_dict = {
   1: 'one',
   2: 'two',
   3: 'three'
}
print("Converting dictionary into set: ", set(numbers_dict))

mystr = 'Hello World'
print("Converting string into set: ", set(numbers_string))
Converting list into set: {
   1,
   2,
   3,
   4,
   5
}
Converting tuple into set: {
   1,
   2,
   3,
   4,
   5
}
Converting dictionary into set: {
   1,
   2,
   3
}
Converting string into set: {
   'H',
   'o',
   'W',
   'd',
   ' ',
   'l',
   'e',
   'r'
}

Suggestion : 4

The constructor is a method that is called when an object is created. This method is defined in the class and can be used to initialize basic variables.,Each time an object is created a method is called. That methods is named the constructor.,The default actions can be defined in methods. These methods can be called in the constructor.,To summarize: A constructor is called if you create an object. In the constructor you can set variables and call methods.

1234567
class Human: def __init__(self): self.legs = 2 self.arms = 2 bob = Human() print(bob.legs)
12345678910111213141516171819
class Plane: def __init__(self): self.wings = 2 # fly self.drive() self.flaps() self.wheels() def drive(self): print('Accelerating') def flaps(self): print('Changing flaps') def wheels(self): print('Closing wheels') ba = Plane()
1234567891011121314
class Bug: def __init__(self): self.wings = 4 class Human: def __init__(self): self.legs = 2 self.arms = 2 bob = Human() tom = Bug() print(tom.wings) print(bob.arms)

Suggestion : 5

A constructor must be defined with the name __init__.,A constructor must be defined with the self keyword in its parameters.,The constructor is always named def __init__(self):.,And the parameterized constructor, this takes one or more arguments.

user[1] = User('Alice', 'Coder', 'Windows') user[2] = User('Bea', 'Marketeer', 'Mac')
user[1].name = 'Alice'
user[1].job = 'Coder'
user[1]....# etc
class Example: def __init__(self): pass
obj1 = Example() # constructor calledobj2 = Example() # constructor called
>>> class Computer: ...def __init__(self, name, speed): ...self.name = name...self.speed = speed...
>>> apple = Computer('Apple', 100) >>> iphone = Computer('Apple iOS', 10) >>> watch = Computer('Watch', 1)

Suggestion : 6

In Python, the method the __init__() simulates the constructor of the class. This method is called when the class is instantiated. It accepts the self-keyword as a first argument which allows accessing the attributes or method of the class.,We can pass any number of arguments at the time of creating the class object, depending upon the __init__() definition. It is mostly used to initialize the class attributes. Every class must have a constructor, even if it simply relies on the default constructor.,In the above code, the object st called the second constructor whereas both have the same configuration. The first method is not accessible by the st object. Internally, the object of the class will always call the last constructor if the class has multiple constructors.,When we do not include the constructor in the class or forget to declare it, then that becomes the default constructor. It does not perform any task but initializes the objects. Consider the following example.

ID: 101
Name: John
ID: 102
Name: David
The number of students: 3
This is parametrized constructor
Hello John
101 Joseph
The Second Constructor
John
23
True
AttributeError: 'Student'
object has no attribute 'age'

Suggestion : 7

That's not a set construction syntax thing. You're running into implicit string literal concatenation, a confusing and surprising corner of the language:

>>> 'a'
'b'
'ab'

Two string literals separated by whitespace are considered one string literal.

rationale = ('This is quite useful when you need to construct '
   'a long literal without useless "+" and without '
   'the indentation and newlines which triple-quotes bring.')

Do you mean

>>> {
   'a'
   'b'
} == set(['ab'])
True

That's just because 2 strings are concatenated to 1 string:

>>> type('a' 'b')
<class 'str'>
   >>> len('a' 'b')
   2
   >>> print('a' 'b')
   ab

Suggestion : 8

The instantiation operation (“calling” a class object) creates an empty object. Many classes like to create objects with instances customized to a specific initial state. Therefore a class may define a special method named __init__(), like this:,the outermost scope (searched last) is the namespace containing built-in names,Attribute references use the standard syntax used for all attribute references in Python: obj.name. Valid attribute names are all the names that were in the class’s namespace when the class object was created. So, if the class definition looked like this:,Although scopes are determined statically, they are used dynamically. At any time during execution, there are 3 or 4 nested scopes whose namespaces are directly accessible:

def scope_test():
   def do_local():
   spam = "local spam"

def do_nonlocal():
   nonlocal spam
spam = "nonlocal spam"

def do_global():
   global spam
spam = "global spam"

spam = "test spam"
do_local()
print("After local assignment:", spam)
do_nonlocal()
print("After nonlocal assignment:", spam)
do_global()
print("After global assignment:", spam)

scope_test()
print("In global scope:", spam)
After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam
class ClassName:
<statement-1>
   .
   .
   .
   <statement-N>
class MyClass:
   ""
"A simple example class"
""
i = 12345

def f(self):
   return 'hello world'
x = MyClass()
def __init__(self):
   self.data = []