+ 2

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

24th Sep 2021, 6:53 PM
🌼Faith🌼
🌼Faith🌼 - avatar
7 ответов
+ 8
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!
24th Sep 2021, 8:15 PM
Lothar
Lothar - avatar
+ 6
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.
24th Sep 2021, 8:02 PM
Arsalan [Inactive]
Arsalan [Inactive] - avatar
+ 3
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. https://code.sololearn.com/crY1D6CrVZiN/?ref=apphraf
24th Sep 2021, 8:48 PM
Per Bratthammar
Per Bratthammar - avatar
+ 1
using recursion
24th Sep 2021, 7:27 PM
Saurabh
Saurabh - avatar
0
Max Lehmann I'm talking about sets not lists. Pls check the question again. Thanks for your contribution.
24th Sep 2021, 7:33 PM
🌼Faith🌼
🌼Faith🌼 - avatar
0
Saurabh Kumar Yadav pls explain more
24th Sep 2021, 7:34 PM
🌼Faith🌼
🌼Faith🌼 - avatar
- 3
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
24th Sep 2021, 7:08 PM
Max Lehmann
Max Lehmann  - avatar