CallMePedro
CallMePedro

Reputation: 91

Python list in list with 2 strings

I have 2 lists of strings. I would like to combine them together to create list in lists like this one below. [['Hello','praet:sg:m1:perf'], ['world', 'subst:pl:acc:n']] How to do it? Somehow create instance of list in list or there is some "python magic"?

Thank you

Upvotes: 1

Views: 105

Answers (5)

Stefan Scheller
Stefan Scheller

Reputation: 953

zip (Python Docs) is what you are looking for. You can stitch together two lists in a list comprehension:

l1 = ['Hello', 'world']
l2 = ['praet:sg:m1:perf','subst:pl:acc:n']

zipped = [list(items) for items in zip(l1,l2)]

print(zipped)

Result:

[['Hello', 'praet:sg:m1:perf'], ['world', 'subst:pl:acc:n']]

Upvotes: 2

Dcoder14
Dcoder14

Reputation: 1939

There are many ways to do that.

ex-1: by using '+'

list1=['Hello', 'world'] 
list2 = ['praet:sg:m1:perf','subst:pl:acc:n']

print([list1]+[list2])

ex-2: by using append()

res =[]
list1=['Hello', 'world'] 
list2 = ['praet:sg:m1:perf','subst:pl:acc:n']

res.append(list1)
res.append(list2)
print(res)

ex-3: by using zip()

list1=['Hello', 'world']
list2 = ['praet:sg:m1:perf','subst:pl:acc:n']

res = [[l1, l2] for l1,l2 in zip(list1, list2)]

print(res)

Upvotes: 1

rdas
rdas

Reputation: 21305

Use zip

list1=['Hello', 'world']
list2 = ['praet:sg:m1:perf','subst:pl:acc:n']

result = [[x, y] for x,y in zip(list1, list2)]

print(result)

Output:

[['Hello', 'praet:sg:m1:perf'], ['world', 'subst:pl:acc:n']]

Upvotes: 1

zedv
zedv

Reputation: 1469

Just add the two list you have to another list:

list1 = ['Hello', 'praet:sg:m1:perf']
list2 = ['world', 'subst:pl:acc:n']

result = [list1, list2]

Another way:

result = []
list1 = ['Hello', 'praet:sg:m1:perf']
list2 = ['world', 'subst:pl:acc:n']

...

result.append(list1)
result.append(list2)

Upvotes: 1

Emma H
Emma H

Reputation: 68

I hope this helps:

list1=['Hello', 'world']
list2 = ['praet:sg:m1:perf','subst:pl:acc:n']

newlist = []

for i in range(len(list1)):
   newlist.append([list1[i],list2[i]])

Upvotes: 1

Related Questions