Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Add Set Items
Next article icon

Python Access Set Items

Last Updated : 06 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Python sets are unordered collections of unique elements. Unlike lists or dictionaries, sets do not have indices so accessing elements in the traditional way using an index doesn't apply. However, there are still ways to work with sets and access their items effectively. This article will guide you through different methods for accessing items in a Python set.

Checking if Item Exists in Set

We can check if a particular item exists in a set using the in keyword:

Python
s = {1, 2, 3, 4, 5} print(3 in s)  # Output: True 

Output
True 

In this example, the expression 3 in s checks whether the number 3 is a member of the s set. The result is True if the item is found in the set and False otherwise.

Let's explore other methods of accessing elements in a set:

Table of Content

  • Iterating Through a Set
  • Getting the Number of Items in a Set
  • Removing and Returning an Arbitrary Item

Iterating Through a Set

To process each item in a set, you can use a for loop:

Python
for i in {1, 2, 3, 4, 5}:     print(i) 

Output
1 2 3 4 5 

Here, the for loop iterates over each item in the numbers set, printing each item to the console. Since sets are unordered, the items may be printed in any order.

Getting Number of Items in a Set

Use len() function to get the total number of items in a set:

Python
s = {1, 2, 3, 4, 5} print(len(s))  # Output: 5 

Output
5 

The len() function returns the number of items in the numbers set. In this case, the output is 5 because there are five items in the set.

Removing and Returning an Arbitrary Item

The pop() method removes and returns an arbitrary item from the set. It raises a KeyError if the set is empty:

Python
s = {1, 2, 3, 4, 5} item = s.pop() print(item)  # Output: 1 (or any other item) print(s)  # Output: Remaining items in the set 

Output
1 {2, 3, 4, 5} 

In this example, the pop() method removes and returns an arbitrary item from the numbers set. The removed item is stored in the item variable and printed to the console. The remaining items in the set are also printed. Since sets are unordered, the item removed by pop() can be any element from the set.


Next Article
Python - Add Set Items

A

anuragtriarna
Improve
Article Tags :
  • Python
  • Python Programs
  • python-set
  • Python set-programs
Practice Tags :
  • python
  • python-set

Similar Reads

  • Python Access Tuple Item
    In Python, a tuple is a collection of ordered, immutable elements. Accessing the items in a tuple is easy and in this article, we'll explore how to access tuple elements in python using different methods. Access Tuple Items by IndexJust like lists, tuples are indexed in Python. The indexing starts f
    2 min read
  • Python - Add Set Items
    Python sets are efficient way to store unique, unordered items. They provide various methods to add elements ensuring no duplicates are present. This article explains how to add items to a set in Python using different methods: Add single set item using add() MethodThe add() method allows you to add
    2 min read
  • Python - Access List Item
    Whether we are working with numbers, strings or other data types, lists provide a versatile way to organize and manipulate data. But how to access specific items in a list? This article will guide you through various methods of accessing list items in Python. Accessing List Items by IndexIn Python,
    3 min read
  • Python Update Set Items
    Python sets are a powerful data structure for storing unique, unordered items. While sets do not support direct item updating due to their unordered nature, there are several methods to update the contents of a set by adding or removing items. This article explores the different techniques for updat
    2 min read
  • Python Remove Set Items
    Python sets are an efficient way to store unique, unordered items. While adding items to a set is straightforward, removing items also offers a variety of methods. This article will guide you through the different techniques available to remove items from a set in Python. Remove single set item usin
    3 min read
  • Check If a Python Set is Empty
    In Python, sets are versatile data structures used to store unique elements. It's common to need to check whether a set is empty in various programming scenarios [GFGTABS] Python # Initializing an empty set s = set() print(bool(s)) # False since the set is empty print(not bool(s)) # True since the s
    2 min read
  • Python Set Coding Practice Problems
    Welcome to this article on Python set practice problems! Here, we’ll explore a variety of engaging Python set practice questions, including topics like Set Operations, Multiset Operations and more. You’ll also practice solving problems like replacing elements with the least greater element, finding
    1 min read
  • Python - Add List Items
    Python lists are dynamic, which means we can add items to them anytime. In this guide, we'll look at some common ways to add single or multiple items to a list using built-in methods and operators with simple examples: Add a Single Item Using append()append() method adds one item to the end of the l
    3 min read
  • Python - Add Items to Dictionary
    We are given a dictionary and our task is to add a new key-value pair to it. For example, if we have the dictionary d = {"a": 1, "b": 2} and we add the key "c" with the value 3, the output will be {'a': 1, 'b': 2, 'c': 3}. This can be done using different methods like direct assignment, update(), or
    3 min read
  • Convert set into a list in Python
    In Python, sets are unordered collections of unique elements. While they're great for membership tests and eliminating duplicates, sometimes you may need to convert a set into a list to perform operations like indexing, slicing, or sorting. For example, if input set is {1, 2, 3, 4} then Output shoul
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences