Home > Mobile >  How to print [1x2, 3x4, 5x6, 7x8, …, 99x100]
How to print [1x2, 3x4, 5x6, 7x8, …, 99x100]

Time:07-10

I try to use for loop to print [1x2, 3x4, 5x6, 7x8, …, 99x100]

Here is my code. I know there is a problem on line4.

a=[]
for i in range(1,100,2):
    for j in range(i 1,i 2,1):
        a.append(i,"*",j)
print(a)

I can use the following code to print 1x2, 3x4, 5x6, 7x8, …, 99x100 , but it's a string not a list

for i in range(1,100,2):
    for j in range(i 1,i 2,1):
        print(i,"*",j,",",end="")

What should I do to get the [1x2, 3x4, 5x6, 7x8, …, 99x100] printed?

CodePudding user response:

You can use zip and range.

res = []
# list(zip([1,3], [2,4])) -> [(1, 2), (3, 4)]
# ------------- range(start, end, step) --------
for o, e in zip(range(1,100,2), range(2,101,2)):
    res.append(f'{o}x{e}')
print(res)

Output:

['1x2', '3x4', '5x6', '7x8', '9x10', '11x12', '13x14', '15x16', '17x18', '19x20', '21x22', '23x24', '25x26', '27x28', '29x30', '31x32', '33x34', '35x36', '37x38', '39x40', '41x42', '43x44', '45x46', '47x48', '49x50', '51x52', '53x54', '55x56', '57x58', '59x60', '61x62', '63x64', '65x66', '67x68', '69x70', '71x72', '73x74', '75x76', '77x78', '79x80', '81x82', '83x84', '85x86', '87x88', '89x90', '91x92', '93x94', '95x96', '97x98', '99x100']

CodePudding user response:

You can change your first code block like so:

a=[]
for i in range(1,100,2):
    for j in range(i 1,i 2,1):
        # use an 
        a.append(f"{i}x{j}")
print(a)

The result is a list of strings:

['1x2', '3x4', '5x6', '7x8', '9x10', … '97x98', '99x100']

CodePudding user response:

Or you can write in one line (this will be more efficient):

res = [f'{o}x{e}' for o, e in zip(range(1,100,2), range(2,101,2))] # ~27.4 µs

and

res = []
for o, e in zip(range(1,100,2), range(2,101,2)):
    res.append(f'{o}x{e}') # ~43.5 µs

CodePudding user response:

More concise code using a list comprehension, f-string and one range counter:

res = [f'{i}x{i 1}' for i in range (1, 100, 2)]
print(res)

Try it online!

CodePudding user response:

People have posted different valid answers. I just wanted to add one more point here. If you dont want the data to be in list and display as you mentioned then you can use below.

res = [f'{i}x{i 1}' for i in range (1, 100, 2)]
print(*res,end= " ")
  • Related