I am having trouble with a list of sets and I think it is because I initialized it wrong, is this a valid way to initialize and add to a list of 5000 sets?
sets = [set()]*5000
i = 0
for each in f:
line = each.split()
if (some statement):
i = line[1]
else:
sets[i].add(line[0])
any advice would be much appreciated
You can use python set() function to convert list to set.It is simplest way to convert list to set. As Set does not allow duplicates, when you convert list to set, all duplicates will be removed in the set.
Therefore, Python does not allow a set to store a list. You cannot add a list to a set. A set is an unordered collection of distinct hashable objects.
A Python Array is a collection of common type of data structures having elements with same data type. It is used to store collections of data. In Python programming, an arrays are handled by the “array” module. If you create arrays using the array module, elements of the array must be of the same numeric type.
We can create list of object in Python by appending class instances to list. By this, every index in the list can point to instance attributes and methods of the class and can access them. If you observe it closely, a list of objects behaves like an array of structures in C.
You are storing a copy of reference to a single set in each of your list indices. So, modifying one will change the others too.
To create a list of multiple sets, you can use list comprehension:
sets = [set() for _ in xrange(5000)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With