1

I have 2 lists as below:

list1 = ["jr", "sr", "manager"]
list2 = ["james", "william", "tim"]

I would like to combine the first element of list1 and then list2 and the pattern goes on.

Expected Output:

list3 = ["jr", "James", "sr", "william", "manager", "tim"]

I have tried the below:

list3 = []
list3.extend(name[0::])
list3.extend(rank[0::1])
print(list3)

but it fails to give me the expected output. Any suggestions?

Natan
  • 71
  • 5

4 Answers4

2

If your lists are always same length just use zip and flatten result:

list1 = ["jr", "sr", "manager"]
list2 = ["james", "william", "tim"]
result = [item for sublist in zip(list1, list2) for item in sublist]
print(result)

Output:

['jr', 'james', 'sr', 'william', 'manager', 'tim']
Daweo
  • 31,313
  • 3
  • 12
  • 25
  • What if both lists aren't of the same length? For example: list1 = ["manager"] list2 = ["james", "william", "tim"] – Natan Jun 20 '20 at 17:56
  • @Natan it will cut longer list to length of shorter, so if `list1 = ["manager"]` and `list2 = ["james", "william", "tim"]` then output is `['manager', 'james']` – Daweo Jun 20 '20 at 18:58
1

Using zip() builtin method:

list1 = ["jr", "sr", "manager"]
list2 = ["james", "william", "tim"]

out = []
for a, b in zip(list1, list2):
    out.append(a)
    out.append(b)

print(out)

Prints:

['jr', 'james', 'sr', 'william', 'manager', 'tim']
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
0

Use a for Loop to access the elements of the bigger list.length(),and through indexing you can have the desired output.

for i in range(len(list1)):

use the append and range fuctionality to all the arguments,and construct an algorithm or even zip command.

0

You can use the built-in zip method to do what you want

men = list(zip(list1, list2))

[('jr', 'james'), ('sr', 'william'), ('manager', 'tim')]

for rank, name in men:
    print(rank, name)

# jr james
# sr William
# manager tim
Artyom Vancyan
  • 5,029
  • 3
  • 12
  • 34