0

My matrix is :

[['f', 'e', 'e', 'd'], ['t', 'h', 'e', 'd'], ['o', 'g']]

Code :

for i in range(cols):
            result = ""
            for j in range(rows):
                result += matrix[j][i]
            temp.append(result)
        return(" ".join(temp))

When I am running the loop, which needs to capture elements row-wise, it throws an error as soon as the element (row = 3, col = 3) in the last row is reached which is not present. Is there any way I can skip the element that is not present by giving any condition like skip if an index does not exist and move on with the next first row again?

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
Aditya Kushwah
  • 343
  • 1
  • 2
  • 8
  • You cannot do `for j in range(len(i))`? – Sohaib Farooqi May 14 '18 at 16:06
  • 1
    Yes, there are ways to do this. But as others point out, you shouldn't be using indexing here in the first place. Just loop over your list *directly* instead of looping over a `range` object. Or if you doggedly insist on using range, then simply interrogate the length before you create the range, as pointed out in the comment above. But really, just loop over your lists directly – juanpa.arrivillaga May 14 '18 at 16:18

3 Answers3

2

You could skip the indices all together, since python's for loop is a for each loop.

result = ""
for column in row:
    for element in column:
        result += element
Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50
0

You could surround your code in a try...except block

try:
    result += matrix[j][i]
except IndexError: 
    pass
Sam
  • 228
  • 1
  • 9
  • try catch are nice ... but in this case its like providing a live-long service of band-aids when selling you a knive instead of teaching you to not cut yourself withit :/ – Patrick Artner May 14 '18 at 17:37
  • i'd never actually recommend it in this case. I was just trying to answer the question as closely as possible – Sam May 14 '18 at 18:02
0

One way for that is to use a try-except to handle the exceptions (IndexError) in any way you want. But what you are trying to do is concatenating characters within each sublist that can be done in a more pythonic way like a list comprehension.

In [1]: a = [['f', 'e', 'e', 'd'], ['t', 'h', 'e', 'd'], ['o', 'g']]
In [2]: [''.join(sub) for sub in a]
Out[2]: ['feed', 'thed', 'og']

And for the final result you can use another join method as following:

In [3]: " ".join([''.join(sub) for sub in a])
Out[3]: 'feed thed og'
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • I think the list comprehension is a distraction here. The key Pythonic principal here is to iterate directly over the sequence rather than using `range` and indexing – juanpa.arrivillaga May 14 '18 at 16:14