Course
Loop Sets
Python Tutorial
This Python tutorial has been written for the beginners to help them understand the basic to advanced concepts of Python Programming Language. After completing this tutorial, you will find yourself at a great level of expertise in Python, from where you can take yourself to the next levels to become a world class Software Engineer.
Loop Sets
A set in Python is not a sequence, nor is it a mapping type class. Hence, the objects in a set cannot be traversed with index or key. However, you can traverse each item in a set using a
for
loop.Example 1
The following example shows how you can traverse through a set using a
for
looplangs = {"C", "C++", "Java", "Python"}for lang in langs: print (lang)
It will produce the following output
CPythonC++Java
Example 2
The following example shows how you can run a
for
loop over the elements of one set, and use the add()
method of set class to add in another set.s1={1,2,3,4,5}s2={4,5,6,7,8}for x in s2: s1.add(x)print (s1)
It will produce the following output
{1, 2, 3, 4, 5, 6, 7, 8}
Practice with Online Editor
Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
Remember to save code(Ctrl
+S
Or
Command
+S
) before run it.