0

I'm curious about how to print the list using nested.

here's the code

students = [["BSIT",["JOSHUA", "CRISA", "JAYMARK"]], ["BSCS",["BOBS", "CARLO", "GERALD"]]]
 
for i,j in students:
    print (i,"\n-",j)

when I try to print it,

BSIT 
- ['JOSHUA', 'CRISA', 'JAYMARK']
BSCS 
- ['BOBS', 'CARLO', 'GERALD']
> 

How can I print element inside the "BSIT" individually? Is there any wrong syntax?

2
  • 3
    Another loop over j…‽ Commented Apr 15, 2021 at 17:22
  • 1
    you probably need to use print (i, "\n-", *j) or if you need each oe on its own line, something in the form of print (i,"\n-".join([""]+j)) Commented Apr 15, 2021 at 17:24

1 Answer 1

1

There's nothing wrong with the syntax, the logic of the code doesn't match with what you are trying to do. Each element in students is in the form of a [String, List]. And within the list contains the students names. If you want to print out the students names, you can do using the following code:

for i,j in students:
    print(i)
    for name in j:
        print("\t", name)
    

The code will retrieve each element and store the String as i and the List as j. We can then iterate through the List and display each of its element as shown.

for i,j in students:
    print(i)
    print(*j)

You can also use the code above to display all the contents of the list within a single line as pointed out by Onyambu.

Sign up to request clarification or add additional context in comments.

2 Comments

I thought it's impossible to name the 'list' like naming the 'j' as name. Thank you so much!
@Carlmalone They're just used to reference items so you can name them as anything you want!

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.