5

How can i implement a C like struct,create an array of such a struct and read such data in Python?

typedef struct Pair{
int first_element,second_element;
}Pair;


Pair array_of_pairs[10];

2 Answers 2

5

Python arrays can contain anything - and they grow as needed so you don't need to put a hard-limit on the size.

Try this - it creates a namedtuple (good way to represent struct like things).

from collection import namedtuple
Pair = namedtuple("Pair", ["first", "second"])

p1 = Pair(1,2)
p2 = Pair(3,4)

list_of_pairs = [p1,p2]

print(list_of_pairs)
Sign up to request clarification or add additional context in comments.

3 Comments

And if I,for example,want to print just the first pair or any other data from my array is it enough to just type print(list_of_pairs[0]) just like in any python list,which i explicitly convert it into an array?
List indexing works just like in C. But you'll get an IndexError if you try to access anything outside the bounds of the list
collections not collection. Try: from collections import namedtuple
1

Use tuples:

pair = (1, 2)
first, second = pair
array_of_pair = [pair, (3, 4)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.