It seems you have a copy-paste error here, as you just have to change the 6 to 4 when you do the slice. Also note that you use two different lists for the range and for the slice. I think you meant this:

for d in range(0,len(codedmessage),4):
    codewordgrid.append(list(codedmessage[d:d+4]))
Answer from tobias_k on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python-rows-with-all-list-elements
Python – Rows with all List elements | GeeksforGeeks
May 1, 2023 - In this, we iterate for each row from Matrix, and check for the presence of each list element, if the present row is returned as a result. If any element is not present, row is flagged off. ... # Python3 code to demonstrate working of # Rows with all List elements # Using loop # initializing list test_list = [[7, 6, 3, 2], [5, 6], [2, 1, 8], [6, 1, 2]] # printing original list print("The original list is : " + str(test_list)) # initializing list sub_list = [1, 2] res = [] for row in test_list: flag = True # checking for all elements in list for ele in sub_list: if ele not in row: flag = False if flag: res.append(row) # printing result print("Rows with list elements : " + str(res))
Discussions

Create a list with certain number of rows and columns in Python - Stack Overflow
I have a problem I can't seem to get right. I have 2 numbers, A & B. I need to make a list of A rows with B columns, and have them print out 'R0CO', 'R0C1', etc. Code: import sys A= int... More on stackoverflow.com
🌐 stackoverflow.com
python - How can I make a list from list of rows? - Stack Overflow
I have this list: d=['-5 -50', '-2 -15 .5', '50;-2e2', '-1 -12', '0,-40'] How i can remove symbol such as , . ;(and also third number if it existі) from this list and make list like that d1=[-5 -5... More on stackoverflow.com
🌐 stackoverflow.com
python - How to extract rows from a list of lists? - Stack Overflow
I have a list of lists and I'm trying to extract rows from list and plot them over a common x-variable. So I'm trying to extract each row at a time using a loop, for i in range(10): tlist = l... More on stackoverflow.com
🌐 stackoverflow.com
Python: read file, store rows as list and create list of rows - Stack Overflow
I have a data file with a certain amount of rows and columns that I import. I want to store the values of each row in a list and finally create a list consisting of the lists of each row, e.g. a More on stackoverflow.com
🌐 stackoverflow.com
February 18, 2015
🌐
TutorialsPoint
tutorialspoint.com › python-rows-with-all-list-elements
Python – Rows with all List elements
my_list = [[8, 6, 3, 2], [1, 6], [2, 1,7], [8, 1, 2]] print("The list is :") print(my_list) sub_list = [1, 2] result = [] for row in my_list: flag = True for element in sub_list: if element not in row: flag = False if flag: result.append(row) print("The resultant list is :") print(result) The list is : [[8, 6, 3, 2], [1, 6], [2, 1, 7], [8, 1, 2]] The resultant list is : [[2, 1, 7], [8, 1, 2]] A list of list is defined and is displayed on the console.
🌐
Dataquest
dataquest.io › home › blog › python list tutorial: lists, loops, and more!
Python List Tutorial: Lists, Loops, and More!
March 11, 2025 - Python isolates, one at a time, each list element from app_data_set, and assigns it to each_list (which basically becomes a variable that stores a list — we'll discuss this more on the next screen): The code in the last diagram above is a much more simplified and abstracted version of the code below: Using the technique above requires us to write a line of code for every row in the data set.
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 60219816 › how-to-extract-rows-from-a-list-of-lists
python - How to extract rows from a list of lists? - Stack Overflow
I have a list of lists and I'm trying to extract rows from list and plot them over a common x-variable. So I'm trying to extract each row at a time using a loop, for i in range(10): tlist = list(zip(*v_avg_store)) tlist[0] print(tlist) x = np.array(steps_store) y = np.array(tlist) plt.plot(x,y) v_avg_store = [100,23,23,45,12,122], [2,1232,123,43,545,645], [234,23,43,556,33,45] ... /usr/local/lib/python3.6/dist-packages/matplotlib/axes/_base.py in _xy_from_xy(self, x, y) if x.shape[0] != y.shape[0]: raise ValueError("x and y must have same first dimension, but "have shapes {} and {}".format(x.shape, y.shape)) if x.ndim > 2 or y.ndim > 2: raise ValueError("x and y can be no greater than 2-D, but have "
Top answer
1 of 6
2

The Answer(s)

Using Python 2.x it's as simple as

list_of_lists = [map(int,l.split()) for l in open('data.txt').readlines()]

but for Python 3.x the map builtin returns a generator, not a list so it has to be written using list comprehension (LC)

lol = [[int(s) for s in l.split()] for l in open('data.txt').readlines()]

BTW, the second possibility works as well in Python 2.x, so from a compatibility POV it could be the preferred approach.

Why does it works?

Let's focus on the second answer, our list of lists (LOL) is built using a nested list comprehension, the outer producing a list of objects produced by the inner one, i.e., lists, hence a LOL as requested...

The fundamental concept is that you need not an explicit loop on the lines of a file because every file object, as returned from the open builtin, has a .readlines method that returns a list of lines, each line represented by a string terminated by the linefeed character.

The elements of this list (the lines) can be split in individual elements using the .split method of strings --- by default split acts on whitespace, so it follows your requirements and we can write, using a LC

[l.split() for l in open('data.txt').readlines()]

obtaining the following LOL

[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']],

as you can see we are close to our target, but the elements of the inner lists are not numbers, but textual repersentations of numbers, i.e., strings.

We have to introduce a further step, that is converting strings to numbers. We have two choices, the builtins int and float, in your case it seems that you want integers so we want int, a function that accepts a single argument (that's not exactly true) either a number or a string.

If we pass to int the outcome of l.split() an error will be raised, because l.split() doesn't return a string but a list of strings... we have to 1. unpack the elements of the lists and 2. pack back the results into a list, in other words it is again a LC!

[int(s) for s in l.split()] # -> [1, 2, 3] for the first line, etc

Let's put the pieces together and you have your answer:

lol = [[int(s) for s in l.split()] for l in open('data.txt').readlines()]

It's really easy (if you already knew all the stuff I tried to explain, that is...)

2 of 6
2

You could use csv module.

import csv
with open('file') as f:
    reader = csv.reader(f, delimiter=" ")
    print([i for i in reader])  

Output:

[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
🌐
GeeksforGeeks
geeksforgeeks.org › pandas › create-a-list-from-rows-in-pandas-dataframe
Create a list from rows in Pandas dataframe - GeeksforGeeks
July 28, 2025 - This method extracts all rows as a list of lists by converting the DataFrame into a NumPy array and then transforming it into a list.
🌐
Reddit
reddit.com › r/learnpython › help with iterating through list of lists to print only columns
r/learnpython on Reddit: Help with iterating through list of lists to print only columns
March 30, 2024 -

Hi, I'm still in the early chapters of Automate the boring stuff.

Chapter 4 q 3 has you iterating through a list of lists to print a heart. You just have to print out the columns in order. It's extremely basic and I thought I figured it out, but my code gives an error.

grid = 
    [['.', '.', '.', '.', '.', '.'],  
    ['.', 'O', 'O', '.', '.', '.'],
    ['O', 'O', 'O', 'O', '.', '.'],
    ['O', 'O', 'O', 'O', 'O', '.'],
    ['.', 'O', 'O', 'O', 'O', 'O'],
    ['O', 'O', 'O', 'O', 'O', '.'],
    ['O', 'O', 'O', 'O', '.', '.'],
    ['.', 'O', 'O', '.', '.', '.'],
    ['.', '.', '.', '.', '.', '.']]  

column = 0 
for x in grid:  
   print(x[column], end='')  
   column += 1

I used this column variable to iterate through the columns. If I put the column number in manually, it works fine. But indexing each list with the column variable doesn't work. It gives this error:

Traceback (most recent call last):
File "C:\Users\Jason\Desktop\Python_\Automate the Boring
 Stuff\4.3 Character Picture Grid.py", line 13, in <module>
    print(x[column], end='')
 IndexError: list index out of range
 .OOOO.

Strangely, at the end of the error, it printed something... I'm not sure where it got that from. Can someone please explain that behavior?

Thank you so much for the help.

Top answer
1 of 5
5
for col in zip(*grid): print(*col) This is generally what zip() does. And IMHO the most straight forward answer. But long hand we want something like this. (As you may not have covered built ins like zip() or *unpacking. I could also see this as an exercise leading into learning the function.) col = 0 while col < len(grid[0]): for row in grid: print(row[col], end = “”) print() #new line col += 1 Take some time understanding both of the above. These are fundamental operations, having a solid ground will help you later. Note: Both of these assume that all of the rows are exactly the same length. Since I don’t know the expected result otherwise, I feel this is a good assumption. What you’re actually doing is printing the diagonal not the column. You see this with “.OOOO.” Which is grid[0][0], grid[1][1]…. grid[5][5]. What’s happening is there are more rows than columns, so once your diagonal gets to the end of the row, it will keep trying to go further, grid[6][6], this is an index that is out of range.
2 of 5
3
"for x in grid" will loop through the *rows*, giving you one full row per iteration. Then "x[column]" will give you the element at THAT row, at that column index But you're adding 1 to column each time, so you'll get grid[0][0] and then grid[1][1] and then grid[2][2] etc There are more rows than columns, so you'll end up incrementing column past the number of actual columns there are, and get the error you see I don't know what you're trying to actually print though, what output do you expect?
🌐
Snakify
snakify.org › two-dimensional lists (arrays)
Two-dimensional lists (arrays) - Learn Python 3 - Snakify
[say more on this!] Such tables are called matrices or two-dimensional arrays. In Python any table can be represented as a list of lists (a list, where each element is in turn a list). For example, here's the program that creates a numerical table with two rows and three columns, and then makes ...
🌐
Quora
quora.com › How-can-I-change-rows-into-columns-in-Python-in-a-nested-list
How to change rows into columns in Python in a nested list - Quora
Answer: I assume that if you have the following list [[1, 2], [3, 4]] you want to make it [[1, 3], [2, 4]] and I assume you don’t use pandas for this. If all of the above is true you can do this with zip, like this: arr = [[1, 2], [3, 4] transposed_arr = zip(*arr) transposed_arr = [list(a...
🌐
DEV Community
dev.to › drvcodenta › accessing-rows-and-columns-in-a-2d-array-and-insert-methodpython-2plo
accessing rows and columns in a 2d array and insert method(python) - DEV Community
March 17, 2024 - In Python, a 2D array (or matrix) is essentially a list of lists. You can access elements, rows, and columns in a 2D array using indexing.
🌐
PythonForBeginners.com
pythonforbeginners.com › home › pandas dataframe to list in python
Pandas DataFrame to List in Python - PythonForBeginners.com
March 17, 2023 - To convert a dataframe to a list of rows, we can use the iterrows() method and a for loop. The iterrows() method, when invoked on a dataframe, returns an iterator. The iterator contains all the rows as a tuple having the row index as the first element and a series containing the row data as ...