Reputation: 357
I am attempting to create list of lists using for loops in python. My plan is to use two separate loops; one loop to create big lists to put the small lists in, and another loop to create the small lists and append them to the big lists.
This is being used to make a 'battleship' type game where there is a 10x10 grid.
This is the chunk of code I am having difficult with:
for i in range(0,10):
(newlist,(i))=[]
The only task this specific code is meant to complete is to create 10 new lists, each with a different name. For example, the first circulation of the loop would create list0
, the second circulation list1
and so on up to list9
.
Theoretically, I see nothing wrong with this code. It also does work when instead of creating a new list, you are putting a string into the new variable.
Whenever I run the program, I get the error
ValueError: not enough values to unpack (expected 2, got 0)
I have no idea why this occurs, and would be very grateful if anyone here could help me out.
Upvotes: 6
Views: 99053
Reputation: 365
sometimes it happen because we declare and set values for two object in one line like this line: a,e=[]
not this one which is correct line a,e=[],[]
Upvotes: 1
Reputation: 44838
You seem to have a variable called list
, which you want to populate with some lists. Your code doesn't work as this syntax is used to extract two pieces of data from the iterable on the right hand side. Clearly, []
is empty, so you can extract nothing out of it.
You could do it like this:
your_list = [list() for x in range(9)]
Note that you shouldn't call the variable list
as there exists a built-in function with the same name that constructs an empty list. Right now the variable makes the built-in unaccessible.
Edit: If you need to have 10 lists of lists:
your_list = [[[] for x in range(9)] for y in range(10)]
Then, your_list
will be a list containing 10 lists of lists.
Upvotes: 5
Reputation: 142641
Better create list with sublists because it is easier to use later,
all_lists = []
for i in range(10):
all_lists.append([])
or shorter
all_lists = [ [] for i in range(10) ]
And now you can access lists using index, ie.
all_lists[0]
Eventually create dictionary - then you can use number or string as index
all_lists = {}
for i in range(10):
all_lists[i] = [] # first version
# or
all_lists[str(i)] = [] # second version
or shorter
all_lists = { i:[] for i in range(10) } # first version
all_lists = { str(i):[] for i in range(10) } # first version
And now you can access lists using number or string, ie.
all_lists[0] # first version
# or
all_lists["0"] # second version
EDIT: to create 10x10 grid you can use
grid = [ [None]*10 for _ in range(10) ]
You can use different value instead of None
as default.
And to get position (x,y)
you can use
grid[y][x]
First is y
(row), second is x
(column)
Upvotes: 0