Reputation: 61
I am a beginner with Python. I recently learned using loops and want to further improve my skills on it.
However, when I try to execute a for loop, the loop returns nothing. The loop itself is trying to extract any element that contains more than 2es, which should return Steven and De Gea.
all_data = [['John','Steven','Mosh'],
['Juan','Mata','De Gea']]
names = []
for y in all_data:
if y.count("e")>=2:
names.append(y)
names
Could someone kindly point out where I did wrong, much appreciate it.
Upvotes: 1
Views: 42
Reputation: 19322
The problem is that your loop is iterating over a list of lists
and not a flat list
.
This means that in your for loop, y
takes the value of a list
. Printing y makes it clear. What you want to do is to iterate over y again
to do check if the condition is met and add the same string to names
.
for y in all_data:
print(y) #<--------
if y.count("e")>=2:
names.append(y)
['John', 'Steven', 'Mosh'] #<-------
['Juan', 'Mata', 'De Gea'] #<------
A working solution (with clearer variable naming) would be -
all_data = [['John','Steven','Mosh'],
['Juan','Mata','De Gea']]
names = []
for sublist in all_data:
for string in sublist:
if string.count("e")>=2:
names.append(string)
names
['Steven', 'De Gea']
Here is a one-liner list comprehension for the same. Ill let you figure out how this is exactly the same as the above nested loop :) -
[string for sublist in all_data for string in sublist if string.count("e")>=2]
['Steven', 'De Gea']
Upvotes: 3
Reputation: 24
Working code:
all_data = [['John','Steven','Mosh'],
['Juan','Mata','De Gea']]
names = []
for y in all_data:
for x in y:
if x.count("e")>=2:
names.append(x)
names
To find out why your code doesn't work try print('y')
in your for loop to see what y iterates over.
Your code example would work if your array was all_data = [['John','Steven','Mosh', 'Juan','Mata','De Gea']
.
Upvotes: 0