DEV Community

Max
Max

Posted on • Edited on

2 1 1

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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs