How to access a specific item in a set (without loops)? | Sololearn: Learn to code for FREE!


How to access a specific item in a set (without loops)?

9/24/2021 6:53:16 PM


8 Answers

New Answer


Nwachi Faith , please provide a bit more information what you are going to achieve with the set. it would also be helpful when you could post your code here. thanks!


If you need to access an item using key or index, you should use a list, tuple, or dictionary. At sets you can only ask if there is an item in them. And for that you can use the keyword "in": "Hi" in {"Hi", "faith"} Which can also be used in a loop. And recursive functions are essentially the same as loops: The function is called inside itself and this can happen several times.


Hi! If we talk about sets, they are a bit special comparing to lists and tuples; they are not ordered. So you can't get its items by an index. So you have to figure out how you want to use your sets. When you fetch an item from a set, it return somewhat random (depending on Python version). So if you don't want to use a for loop as you said, you can instead use iter() to initialize a iterator, and then get the items, one by one, with next(). (That is what 'for' does.) Or you can use pop(), but then the poped item will disappaer from the set.



using recursion


Max Lehmann I'm talking about sets not lists. Pls check the question again. Thanks for your contribution.


Saurabh Kumar Yadav pls explain more


example : list=[1,2,3] or ["a","b","c"] then use: print(list[0]) this gives the first argument of the list print(list[2]) —> Output 3 remember to use str() or int() when using numbers or strings