Iterate through a list of integer and lists in Python

I want to iterate through a list that contains a mix of lists and non-list elements. Here's an example:

a = [[1, 2, 3, 4, 5], 8, 9, 0, [1, 2, 3, 4, 5]] 

I know how to iterate through a mandatory list of lists, but in this case I don't know how to do it. My objective is to compare one value of the nested list with another value in the list. For example in this case: [1, 2, 3, 4, 5] and 8

Upvotes: 3

Views: 20589

Answers (4)

Rodrigue
Rodrigue

Reputation: 3687

A slightly different version than the answer from jgritty. The differences:

  • we use the filter() built-in to extract the int elements from your list
  • we keep the integers in a set instead of a list
  • we iterate over a copy of a, so that we can safely remove elements from a itself at the same time
  • use list comprehension to remove members of nested lists that are already in the main list

    a = [[1, 2, 3, 4, 5], 5, 6, 7, 8, [9, 0, 1, 8]]
    print a
    
    numbers = set(filter(lambda elem: type(elem) is not list, a))
    
    for elem in a:
        if type(elem) is list:
            elem[:] = [number for number in elem if number not in numbers]
    
    print a
    

Upvotes: 3

jgritty
jgritty

Reputation: 11925

Is this what you want:

thelist = [[1, 2, 3, 4, 5], 5, 6, 7, 8, 10, [9, 0, 1, 8]]
# Remove the 5 from the first inner list because it was found outside.
# Remove the 8 from the other inner list, because it was found outside.
expected_output =[[1, 2, 3, 4], 5, 6, 7, 8, 10, [9, 0, 1]]

Here's a way to do it:

thelist = [[1, 2, 3, 4, 5], 5, 6, 7, 8, [9, 0, 1, 8]]

expected_output =[[1, 2, 3, 4], 5, 6, 7, 8, [9, 0, 1]]

removal_items = []

for item in thelist:
    if not isinstance(item, list):
        removal_items.append(item)

for item in thelist:
    if isinstance(item, list):
        for remove in removal_items:
            if remove in item:
                item.remove(remove)

print thelist

assert thelist == expected_output

Upvotes: 4

seyed
seyed

Reputation: 2055

a = [[1, 2, 3, 4, 5], 8, 9, 0, [1, 2, 3, 4, 5]]
for x in a:
    if type(x) is list:
        for y in x:
            print y
    else:
        print x

or use

isinstance(x, list)

Upvotes: 2

Rodrigo
Rodrigo

Reputation: 400

You can check if the object of the iteration is a ListType (http://docs.python.org/library/types.html) and iterate it further.

I cant remember now the exact command but there is something like type(x) that you can use to get the object's type.

Upvotes: 0

Related Questions