list to set python code example

Example 1: add list to set python

set.update() or |=

>>> a = set('abc')
>>> l = ['d', 'e']
>>> a.update(l)
>>> a
{'e', 'b', 'c', 'd', 'a'}

>>> l = ['f', 'g']
>>> a |= set(l)
>>> a
{'e', 'b', 'f', 'c', 'd', 'g', 'a'}

Example 2: empty set python

# Distinguish set and dictionary while creating empty set

# initialize a with {}
a = {}

# check data type of a
print(type(a))

# initialize a with set()
a = set()

# check data type of a
print(type(a))

Example 3: convert list to set python

names = ['Barry', 'Alice', 'Bob', 'Bob']

unique_names = set(names)
# Result:
# {'Alice', 'Barry', 'Bob'}

Example 4: python set to list

pokemon_set = set(['Pikachu', 'Bulbasaur', 'Koffing' , 'Spearow', 'Vulpix'])
print(pokemon_set)
pokemon_list = list(pokemon_set)
print(pokemon_list)