0

I want to save some data from Twitter and I would to use a 2-dimensional array in order to save all hashtags in the first row and all external urls in the second one, with dynamic cols.

I've implemented this:

hashtag_extLink = 2 * [[]]

...
...

if field == "hashtag":
    hashtag_extLink[0].append(x)
elif field == "ext_link":
    hashtag_extlink[1].append(y)
else:
    pass

but, when I will print the hashtag_extLink using this statement:

for row in range(len(hashtag_extLink)):
    print("Row %d" % row)
    for col in range(len(hashtag_extLink[row])):
        print(hashtag_extLink[row][col], end='')
    print("")

I get:

Row 0
xy
Row 1
xy

that is the append() function add value to both rows. How can I fix? Have I to use Numpy?

Thank you in advance.

3 Answers 3

3

Defining a 2D array like this: x = 2 * [[]] puts the same list in both places in the container list as is happening in your case.

Try defining the array like x = [[],[]]

>>> x = [[],[]]
>>> x[0].append(1)
>>> x
[[1], []]
Sign up to request clarification or add additional context in comments.

1 Comment

Solved in this way. Thank you very much.
0

If you know the sizes,

ar = []
for i in range(5):
   ar.append([])
   for j in range(2):
       ar[i].append(1)

Comments

0

You can Define Dynamic 2D array and initialized with 0 values

def initialize_array(rows, cols): l1 = [[0 for i in range(cols)] for j in range (rows)] print (l1)

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.