简体   繁体   中英

List of tuples of 2 elements using a list comprehension

I want to use a list comprehension to initialize a list of tuples that has a 2 elements in it, my attempt is as follows:

SIZE = 10
possible_positions = [(x, y) for x, y in range(0, SIZE)]

But that gives me an error:

TypeError: cannot unpack non-iterable int object

What is the right way to do it? I know I can use a for loop, but I want to know anyway.

range return a single value per iteration, you should use zip combined with range in the following way:

zip(range(SIZE), range(SIZE))

Using zip will also save you the trouble of creating the list of tuples so calling list(zip(range(SIZE), range(SIZE))) will give you the end result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM