Printing individual items of a set - python

Is there a way to print an individual item from a set? In the same way which you would print items of a list by referencing values between 0 and size of the list.
I was trying to reference items by using print(set_name[i]). But was receiving an error for trying to reference an item in this way. I was able to print the full set with print(set(name_set)), so there was not an issue with defining the values.

Indexing is not supported in set. If you want to get an element from a set, you should either cast it to list (Note that set is unordered), or use an iterator:
for element in <YOUR_SET>:
if element == <DESIRED_VALUE>:
break
print(element)

Related

Moving the last element in a list to a new list

I am trying to move the last element in a list to a different one.
I have tried
test_list = ["1","2","3","4","5","6"] test_list2 = []
test_list2.insert(0, test_list.pop(test_list[-1]))
but it seems to give an error.
The list pop method takes an index, not an object. You can pass -1 to it to get the last item from the list, or pass nothing at all since that's the default.
test_list2.insert(0, test_list.pop())

Python : initializing list and dictionary

I am new to Python. while initializing a list
mylist = list()
mylist[0]="hello"
gives error .It only works
mylist.append("hello")
but if i do same with dictionary
mydict ={}
mydict["one"]="hello"
it works.
why i dont need to do
mydict['one'].append('hello')
why things are different for different structures.
If you update a dict like this:
d['c'] = 3
... there is no need for d['a'] and d['b'] (or any item at all, for that matter) to be present in that dict. The key of a dictionary item does not imply any specific structural properties of your dict object.
However, if you want to update a list like this:
l[5] = 'a'
... the indexes 0 through 5 absolutely must exist. The index not only serves as a handle for an element in the list, but also has structural properties. If l[5] does exist, you can be absolutely sure that indexes 0 through 4 do as well. And you need that certainty.
Imagine you could do l[5] = 'a' on an empty list. What would len(l) return? 1? 6?
Both cases would cause this to fail:
for i in range(len(l)):
print(l[i])
One can argue that l[<index>] = 'a' could implicitly append that value if index-1 already exists or if the list is empty and the desired index is 0. In order for this to reliably work, you would need to ensure that index-1 exists before adding values like this, while, when using append(), you are guaranteed that your value will be added to the list (except for potential edge cases like memory starvation).
If you add an element to a dictionary you connect to a key.
In your case you connect the element 'hello' to your key 'one'
To add an element to a list you will have to use the function list.append.
You use list[x] to get the element at position x.

Removing an element from a set that matches an element in a list

I'm having trouble removing entries from a set.
# Remove all out-of-stock items from our list
# This is O(n^3), unfortunately.
for x in oos:
for asin in asins:
if x == asin[0]:
del asin
'asins' is a set of tuples, created like this:
asins.add(tuple((asin, c, s)))
oos is a list. I'm trying to remove every entry in 'asins' that exists also in 'oos'. Unfortunately, the "del asin" doesn't actually work, as it doesn't delete the entry from 'asins'.
del asin used like that will just delete the local variable asin but not the actually referenced object, and especially not the object that is contained in the set.
Instead, you would need to call set.remove to remove the element:
asins.remove(asin)
However, you don’t actually need to loop through the set to remove an item from it. The whole benefits of sets is that you have constant time access, so you can check membership in constant time, making looping over it rarely useful.
Since you’re storing complex tuples though, and you only identify an element by the first tuple element, you cannot do that here. What you should do is switch to a more appropriate collection. In your case, you want a dictionary:
# convert your set of tuples to a dictionary
# ideally, you would store the data like this in the first place
asins = { asin[0]: asin for asin in asins }
Then you can just do the following:
for x in oos:
del asins[x] # here, you can use del
That would be O(n) in the average case.
You can do this readily with a generator expression. It shouldn't be that inefficient, but I wouldn't call it efficient either.
asins = {t for t in asins if t[0] not in set(oos)}
Note that this creates a new set. This is probably for the best as you cannot iterate over a set and change it in place. For example, changing del asin to asins.remove(asin) will raise a RuntimeError.

Indices of cross-referenced lists

I'm cross-referencing two lists to find which items coincide between the two lists. The first list orig is 32 items in size, and I'm cross-referencing it with a much-larger list sdss which is 112,000 items in size. So far this is what I've got:
for i in range(0,len(orig),1):
if orig[i] in sdss:
print('\n %s' % (orig[i]))
This gives me the items that are the same between the two lists, however, how would I efficiently return the indices (or location) of cross-referenced items inside of the sdss list (the larger list)?
EDIT: I guess I should've been clearer. I am actually cross-referencing two arrays with ints, not strings.
If the order is not of importance you can use set intersection to find the unique common elements and list comprehension to get the index and element as tuple
[(sdss.index(common_element),common_element) for common_element in set(orig) & set(sdss)]
Note that "index" raises ValueError if the value is not found in the list but in this case the value WILL exist in sdss. So, no need to worry about nonexistent elements throwing errors.
You can also use numpy.intersect1d
You can use .find() which gives the index of an item in a list, but returns -1 on failure:
for item in orig:
index = sdss.find(item)
if index != -1:
print("\n %d" % index)
I modified how you iterated because you don't need the index in orig; you need each item. BTW, you could have used range(len(orig)) because your start and step arguments are already the defaults.

How do i remove an item from a list and store it into a variable in python

so i want to remove an item from a list and store it into the variable at the same time in python. I tried a sample code like this:
rvals = []
rvals.append("row")
r = rvals.remove("row")
print(r)
but it turns out this doesnt really work and it gives r a NoneType value instead of removing what i wanted and storing it. Is there a way to do this?
list.remove(x)
Remove the first item from the list whose value is x. It is an error
if there is no such item.
So, as stated in the docs, you will not get the value returned.
This can help:
value = "row"
rvals = []
rvals.append(value)
print rvals.pop(rvals.index(value))
Or just use pop(), if you only want to remove and get the last inserted item:
value = "row"
rvals = []
rvals.append(value)
print rvals.pop()
Output:
row
Printing a removed element from the list using remove() method generally results in None.
Hence, a better approach is to, first store the element to be removed and then remove it from the list.

Categories