DEV Community

Max
Max

Posted on • Edited on

Python set tutorial

Python set is an unordered collection of unique elements. It's used to eliminate duplicates and to perform common math operations like union, intersection, and difference on datasets.

  1. Creating a set of unique strings:
unique_fruits = {"apple", "banana", "orange"}
Enter fullscreen mode Exit fullscreen mode
  1. Creating a set from a list, which automatically eliminates duplicates:
numbers = [1, 2, 3, 4, 2, 5, 1, 6]
unique_numbers = set(numbers)
Enter fullscreen mode Exit fullscreen mode
  1. Performing set operations, such as union and intersection:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
union = set1 | set2
intersection = set1 & set2
Enter fullscreen mode Exit fullscreen mode

Print python set using loop

To print each element of a set using a loop in Python, you can iterate over the set using a for loop. Here's an example:

my_set = {1, 2, 2, 3, 4, 5, 3}

for element in my_set:
    print(element)
Enter fullscreen mode Exit fullscreen mode

In the code above, we create a set called my_set that contains seven elements. We then use a for loop to iterate over the set, and print each element using the print() function.

output:

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

You can replace my_set with any set that you want to print using a loop.

Explore Other Related Articles

Python tuple tutorial
Python Lists tutorial
Python dictionaries comprehension tutorial
Python comparison between normal for loop and enumerate
Python if-else Statements Tutorial

Top comments (0)