[vc_row css_animation=”” row_type=”row” use_row_as_full_screen_section=”no” type=”full_width” angled_section=”no” text_align=”left” background_image_as_pattern=”without_pattern”][vc_column][vc_column_text]

Sets in Python

[/vc_column_text][vc_separator type=”normal” up=”1″][vc_column_text css=”.vc_custom_1571090481975{background-color: #f6f6f6 !important;}”]

Sets in Python are a collection of elements that have no particular order and lack indexing.

[/vc_column_text][vc_empty_space height=”20px”][vc_column_text]

WHAT IS A SET IN PYTHON?

Like tuples and arrays, sets in Python are a collection of objects. The elements in sets has no particular order and therefore lack indexing. Thus, it is not possible to remove an individual element from a set.

 

The elements in sets has no particular order and therefore lack indexing

[/vc_column_text][vc_empty_space height=”30px”][vc_column_text]

[/vc_column_text][vc_empty_space height=”10px”][vc_separator type=”normal” up=”1″][vc_empty_space height=”10px”][vc_column_text]

How to create a Tuple in Python?

The syntax for creating a Sets is,

 

setName = {value1, value2, value3, and so on.. }
  • First you give the set a name
  • Then assigns all values within the curly brackets , where each value is separated by a comma  “,”.
  • Note that a Set is created with curly brackets, unlike the array that is created with brackets [].

[/vc_column_text][vc_empty_space height=”30px”][vc_separator type=”normal” up=”1″][vc_empty_space height=”10px”][vc_column_text]

Example – How to create Sets in Python

Let’s take a quite simple example on how to create a Set in Python

 

sport_set = {"Tennis", "Football", "Ice Hockey"}
print(sport_set)
print(type(sport_set))

 

The result then becomes

 

{'Tennis', 'Football', 'Ice Hockey'}
<class 'set'>

 

 

Note that there are no indexes in sets. Thus, you cannot remove a single element from the set that you can with tuple and arrays.

However, you can iterate through the entire list with a for loop:

 

for i in sport_set:
    print(i)

 

We will get

 

Tennis 
Football 
Ice Hockey

[/vc_column_text][vc_empty_space height=”20px”][vc_column_text]

For more information about Sets in Python we recommend the Python Docs website

[/vc_column_text][vc_empty_space height=”20px”][vc_column_text]

[/vc_column_text][vc_empty_space height=”10px”][vc_separator type=”normal” up=”1″][vc_empty_space height=”20px”][/vc_column][/vc_row][vc_row css_animation=”” row_type=”row” use_row_as_full_screen_section=”no” type=”full_width” angled_section=”no” text_align=”left” background_image_as_pattern=”without_pattern”][vc_column][vc_column_text]

Previous Page    |    Next Page

[/vc_column_text][vc_empty_space][/vc_column][/vc_row]