Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

making an array of sets in python

Tags:

python

set

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

like image 359
Alex Brashear Avatar asked Jul 12 '13 17:07

Alex Brashear


People also ask

How do you create an array set in Python?

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.

Can I have a list of sets in Python?

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.

What is set array in Python?

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.

Can you create an array of objects in Python?

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.


1 Answers

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)]
like image 166
Rohit Jain Avatar answered Sep 29 '22 06:09

Rohit Jain