-6

If I have 2 lists:

list1 = ["X","Y","Z"]
list2 = [1,2,3] 

How can I combine them to make a another list:

list3 = [[1,"X"],[2,"Y"],[3,"Z"]]

Thanks in advance!

4
  • 6
    I think I explained this in my answer to your previous question. Commented Apr 16, 2014 at 17:33
  • @thefourtheye, Yeah, I thought this looked familiar Commented Apr 16, 2014 at 17:34
  • I Apologize, if this is a duplicate question. I'm new to python so couldn't really link and undertand the relationship between this and my previous question. Especially with the sum and dictionary parts of some answers. Sorry again. Commented Apr 16, 2014 at 17:40
  • @DejaVu Nevertheless, I have answered to show how you could use it specifically in your case. Commented Apr 16, 2014 at 17:41

1 Answer 1

1

Just use zip to get tuples of values at corresponding indices in the two lists, and then cast each tuple to a list. So:

[list(t) for t in zip(list1, list2)]

is all you need to do.

Demo:

>>> list1 = ["X", "Y", "Z"]
>>> list2 = [1, 2, 3]
>>> list3 = [list(t) for t in zip(list1, list2)]
>>> list3
[[1, 'X'], [2, 'Y'], [3, 'Z']]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.