Python 2D list slicing where one list is full of empty strings

Viewed 91

So say I have a 2D list like:

[
  [
    "9743",
    "user3"
  ],
  [
    "435",
    "user2"
  ],
  [
    "5426",
    "user8"
  ],
  [
    "",
    ""
  ],
  [
    "9743",
    "user9"
  ]
]

Where the index of that list of empty strings is unknown. Is there an easy way to slice the list so that everything after and including that list with empty strings is removed just keeping the stuff before it?

5 Answers

If you are sure that you have ['',''] try this:

lst = [[ "9743", "user3"],[ "435","user2"],["5426","user8"],["",""],["9743","user9"]]

lst[:lst.index(['',''])]
# Output
# [['9743', 'user3'], ['435', 'user2'], ['5426', 'user8']]

If you are not sure that you have ['',''] try this:

lst = [[ "9743", "user3"],[ "435","user2"],["5426","user8"],["9743","user9"]]
try:
    out = lst[:lst.index(['',''])]
except ValueError:
    out = lst

Output:

[['9743', 'user3'], ['435', 'user2'], ['5426', 'user8'], ['9743', 'user9']]

You can use itertools.takewhile:

from itertools import takewhile
list(takewhile(lambda x: x != ['', ''], the_list))

NB. I named the list "the_list"

output:

[['9743', 'user3'], ['435', 'user2'], ['5426', 'user8']]

If you want to stop at any item being '':

from itertools import takewhile
list(takewhile(lambda x: '' not in x, l))

Iterate through each item in the list, slice the list when the empty value is found and break.

for i in range(len(lst)):
  if lst[i][0] == "" and lst[i][1] == "":
    lst = lst[:i]
    break

Using iter with sentinel:

list(iter(iter(lst).__next__, ['', '']))

You can lose a for-loop like this: (with x being your list)

output = []
for pair in x:
    if pair != ['', '']:
        output.append(pair)
    else:
        break   # Breaking as soon as there is an empty pair.

The output is:

[['9743', 'user3'], ['435', 'user2'], ['5426', 'user8']]
Related