Adding an unique item to a set [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
The syntax for checking if an item is already in a list and then adding it to a list if it is not is:
foo = []
if item not in foo:
foo.append(item)
# do something
This can execute code on the condition that the item is not in foo. This syntax seems to duplicate the logic of a set datatype in python, yet the following syntax does not exist;
bar = set()
if not bar.add(item):
# do something
but add() returns nothing, so this is not possible. So how does one execute some logic conditionally on an item being in a set?
Note: the reason a set is desired is the operation of adding a unique value to a set is of O(1), whereas the same operation is O(n) on a list.

Just remove the if.
bar = set()
bar.add(item):
# do something
Note that you have foo.append(item) when using a list. The only thing that changes is the function name when you use a set.

Related

I have a list in which items are getting added at any index dynamically , so i want to get the latest element added in list? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
a = [5,2,7]
If 2 is the latest element added in a then return 2 .
You can use this syntax:
>>> list_ = [0, 1, 2]
>>> list_[-1]
2
There is no direct way of knowing how a list was modified. Python does not keep track of this information. This means you would have to keep a copy of the list before updating it and run something like
a = [5,2,7]
old_a = a.copy()
a[1] = 0
[old_a[i] for i,v in enumerate(a) if old_a[i]!=v]
However, if you are able to keep track of this, you are certainly able to keep track of the added value, and to run the tests before adding it to the new list. In summary, the design of what you are doing should probably be reconsidered.

Append to list or create new list [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want to add an element to a list, but the list might not exist yet. In which case, I'd create a list of that single element. It might be an entry in a dictionary. It's my responsibility to add to a particular field - hence the append. But, if it's the first time I'm doing it, the key doesn't even exist in the dictionary yet. Hence the set to a list of a single element.
So in a nutshell, the following
if 'dependencies' in userdata:
userdata['dependencies'].append('foo')
else:
userdata['dependencies'] = ['foo']
This feels very unpythonic and ugly. What are some better options?
use try...except like below:
try:
X.append('foo')
except NameError:
print("you need create list first. I create list for you. then append.")
X = ['foo']
EDIT : base on your editing question:
from collections import defaultdict
userdata = defaultdict(list)
userdata['dependencies'].append('foo')

It it worth to use a Dict with only keys and null values? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
So in my niche use case I want to create a hash map in python to store a large list dataset. This list has a key value as a tuple (i.e (1,2)) and my goal is to search the list and see if the tuple exists.
I know this is achievable with a regular list but I wanted the time complexity of O(1) with the hash map functionality. But when adding elements to the dictionary, I am doing this:
dictionary[(1,2)] = None
Because I couldn't care less about the value associated with the key.
Is this good coding practice or is there something else I should use?
If you don't give a toss about the value, you can use a set. From the python source code (line 4 of Objects/setobject.c):
Derived from Lib/sets.py and Objects/dictobject.c.
If you need to iterate over a set, you should use a list or do the conversion as needed.
I would suggest using defaultdict. By default, any values not in the dictionary would be False.
from collections import defaultdict
lookup = defaultdict(bool)
lookup[(1,2)] = True
Examples:
l = [(1,2), (3,4), (5,6)]
for e in l:
lookup[e] = True
print(lookup[(3,4)])
# True
print(lookup[(8, 9)])
# False

Python 3 - Extract sub-dictionary values from a list of dictionaries [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have a list of data with 10 elements called DATA.
Each element is a dictionary (DATA[0] is a dictionary, DATA[1] is a dictionary, .. DATA[9] is a dictionary).
Each of these dictionaries has a key called "Date".
Is there any way I can extract the individual values corresponding from the 'Date' key from each of these 10 dictionaries into their own separate list?
In the end, my list would be NEWLIST = {DATA[0]['Date'], DATA[1]['Date'], .... , DATA[9]['Date']).
Is there any way to do this without a for loop?
you can try list comprehension:
NEWLIST = [x["date"] for x in DATA]
This should be a straightforward list comprehension.
If you're not familiar with that construct, I recommend that you find and work through a tutorial on the topic.
Instead of stepping explicitly through the list, just iterate over the list.
new_list = [data_dict['Date'] for data_dict in DATA]
Note that I've changed all but the original list name to conform to PEP8 guidelines.

Convert tuple to string in python 3 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm tyring to receive data from mysql database via python . In the database I have the value ON_1 when I receive it in python I receive it as tuple : (('ON_1',),) Any help to get it in python in its normal form ON_1
Access the first value of the first tuple, and then access the first value of the resulting tuple:
result[0][0]
This gets the first item of the first tuple to get ("ON_1",) and then gets the first item of that tuple to result in "ON_1".
A nested tuple can be access just like a nested list.
>>> x = (('ON_1',),)
>>>
>>> x[0] # this accesses the first level
('ON_1',)
>>> x[0][0] # this accesses the second level
'ON_1'

Categories