bab
bab

Reputation: 2169

How does python have different data types in an array?

Python can have a list with different data types in it i.e. [1,"two",3]. Python was implemented in c, so how would I create an array with different data types in it using c?

Upvotes: 1

Views: 4751

Answers (4)

tzot
tzot

Reputation: 95911

In Python, there are no “raw” values; everything is an object and knows its type. Even integers are objects (try printing (1).__class__ or 1 .__class__). Everything you do in C with Python objects, you do through a PyObject * (a pointer to the object).¹

A Python list is a dynamic (i.e. resizable) array of PyObject *. Since every object knows its type, the list doesn't have to be declared as having members of a specific type.

¹ Also note: Python does not have “variables” in the usual sense (C, BASIC, Pascal etc), where a typed variable contains a value; it has namespaces and names (actually, dictionaries mapping strings to objects; a namespace is a dictionary, its keys are the names, its values are the pointers to the objects pointed to by each name).

Upvotes: 1

Ed Swangren
Ed Swangren

Reputation: 124642

So, I have no idea how it is implemented in Python, but in C there are ways to operate on generic data. in its most simple form:

void *array[size];

Now you have an array full of void*. Each void* can point to anything. You would want some extra information as well to tell you the size of the thing it points to.

typedef struct {
    void *data;
    size_t size;
} elem;

You could represent the actual type if needed via a variety of methods. You can use unions to hold one of N types in the same variable. Anyway, the point is that there are various ways to do operate on generic data in C.

Upvotes: 4

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272487

how would I create an array with different data types in it using c?

You can't; C is a statically-typed language.

You can, however, use things like unions:

typedef union {
    int i;
    float f;
} Foo;


Foo array[3];

array[0].i = 3;
array[1].f = 4.2;
...

You can also use void * to point at any objects you like, but this requires careful memory management.

Upvotes: 3

larsks
larsks

Reputation: 311516

What if your array consisted of C structs of the form:

struct slot {
  int type;
  char *data;
};

Now you have an array that can contain arbitrary types of data, as long as you can represent them as pointers-to-char.

This isn't, of course, how Python does it; the point is that there doesn't have to be any connection between how your application handles data and how your implementation language handles data.

Upvotes: 3

Related Questions