1

This code below is to make a list of the bigger number of the two lists in the same index positions. How can I rewrite this code with a while loop instead of a for loop?

 a = [7,12,9,14,15,18,12]
 b = [9,14,8,3,15,17,15]
 big = []
 for i in range(len(a)):
     big.append(max(a[i],b[i]))
 print(big)
 [9, 14, 9, 14, 15, 18, 15]

5 Answers 5

2

You can use pop() in order to poop the first item of both lists each time till a or b evaluates as True (it's contain items):

In [15]: while a:
            big.append(max(a.pop(0),b.pop(0)))
   ....:     

In [16]: big
Out[16]: [9, 14, 9, 14, 15, 18, 15]
Sign up to request clarification or add additional context in comments.

Comments

1

One way is this with while

a = [7, 12, 9, 14, 15, 18, 12]
b = [9, 14, 8, 3, 15, 17, 15]
big = []
i = 0
while i < len(a):
    big.append(max(a[i], b[i]))
    i += 1
print big

Comments

1

Using zip and list comprehension:

a = [7, 12, 9, 14, 15, 18, 12]
b = [9, 14, 8, 3, 15, 17, 15]
big = [max(t) for t in zip(a, b)]

Using while:

a = [7, 12, 9, 14, 15, 18, 12]
b = [9, 14, 8, 3, 15, 17, 15]

big = []
i = 0
while i < len(a):
    big.append(max(a[i], b[i]))
    i += 1

Comments

0

You can try this :

a = [7,12,9,14,15,18,12]
b = [9,14,8,3,15,17,15]
big = []
i=0
while i<len(a):
    if a[i]<b[i]:
        big.append(b[i])
        i+=1
    else:
        big.append(a[i])
        i+=1
print(big)

Comments

0

You can also try with zip() and list comprehension like so:

a = [7,12,9,14,15,18,12]
b = [9,14,8,3,15,17,15]
big = [max(c) for c in zip(a,b)]
print big

Output:

[9, 14, 9, 14, 15, 18, 15]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.