1

I have a list of lists of strings, and I would like to iterate through the 2nd index in each sublist. But, instead of assessing each string it is assessing each character of each string... here is what i mean:

Current Code:

fruit = [['bananna',"apple",'grape'],['ham',"sammy",'canada']]    
for l in range(len(fruit)):  
    for i in fruit[l][1]:    
        print i  

Desired output:
apple
sammy

Current output:
a
p
p
l
e
s
a
m
m
y

Really I would like to take some action with each string. Search for that string in another list but right now it appears to be assessing every character of the strings I want to look at instead of the string as a whole... not sure why?

2 Answers 2

3

What you are doing:

for l in range(len(fruit)): #you have the inner_loops in each iteration  

    for i in fruit[l][1]: # You already have what you want in fruit[l[1]

        #you are now getting charcter by character from each value

What should do:

Just skip a loop. And it is more pythonic to iterate by value, not by index.

fruit = [['bananna',"apple",'grape'],['ham',"sammy",'canada']]    
for l in fruit:      
        print l[1]
Sign up to request clarification or add additional context in comments.

Comments

1

Solution:

>>> for l in fruit:
...     print(l[1])
... 
apple
sammy

It works because the for statement allows to iterate over the elements of a list (no index needed).

Original problem:

1 fruit = [['bananna',"apple",'grape'],['ham',"sammy",'canada']]    
2 for l in range(len(fruit)):  
3    for i in fruit[l][1]:    
4        print i  

The problem is in line 3:

  • fruit[l] is one of the sub-lists (e.g. ['banana', 'apple', 'grape']).
  • fruit[l][1] is the second item in this list ('apple').
  • for i in fruit[l][1] iterates over the string ('apple'), which picks up each character.

4 Comments

Strings are iterable in Python. What's happening is that in for i in fruit[l][1], you are iterating over every character in the second string in every sub-list.
While this code may answer the question, providing additional context regarding why and/or how it answers the question would significantly improve its long-term value. Please edit your answer to add some explanation.
Thank you for your feedback @JasonMc92
Thank you, @CarlosMermingas, for the edit. Very well done!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.