0

This is what I am trying to do: part 1: I look for names and ages in a text using regex and putting them is separate lists. part 2: Then I want to create a 3D list that would store name and age pairs.

Part one works out fine. Then I try to do part two and the problem starts.

(In this example) My names list look like this: ['Peter', 'Barbara', 'John'] My ages look like this: ['11', '7', '103']


Python 3.11 code:

import re
def f1(t):
    #part1
    names = re.findall("\[A-Z\]+\[a-z\]\*", t)
    ages = re.findall("\[0-9\]+", t)

    #part2
    new_array = [["", ""]]*len(names)
    
    for i in range(len(new_array)):
        new_array[i][0] = names[i]
        new_array[i][1] = ages[i]
    
    return new_array

print(f1("Peter is 11, Barbara is 7 and their grandfather John is 103 !"))

What I am expecting as output: [['Peter', '11'], ['Barbara', '7'], ['Jhon', '103']]

What I get as output: [['John', '103'], ['John', '103'], ['John', '103']]

  • Your problem is entirely covered by the duplicate. As a side-note, presizing `list`s is generally not considered Pythonic; your code would be more idiomatic (and not have this problem, due to the lack of nested list multiplication) if you just initialized `new_array = []`, then did `for name, age in zip(names, ages): new_array.append([name, age])` avoiding (weirdly slow) manual indexing, and appending to the `list` as you go. – ShadowRanger Jan 25 '23 at 14:13

0 Answers0