Home > Enterprise >  Filling a 2D list with name and family name
Filling a 2D list with name and family name

Time:07-25

Trying to put a string with full names into a 2D list, I get an error list out of range, how can I fix it?

Example y[0][0] should contain "Charbel", and y[0][1] should contain "Daoud"...

string1 = "Charbel Daoud, Manuella Germanos, Anis Ismael"

x= string1.split(",")
print(x)

y = [][1]
i=0
for j in x:
        div = []
        div = j.split(" ")
        y[i][0] = div[0]
        y[i][1] = div[1]
        i =1
    
print(y)

CodePudding user response:

You were getting an error because you were trying to index an empty list y = [][1].

You can do that with a list comprehension:

[i.split(' ') for i in string1.split(', ')]

Output:

[['Charbel', 'Daoud'], ['Manuella', 'Germanos'], ['Anis', 'Ismael']]
  • Related