简体   繁体   中英

single vs double square brackets in python

I get different results when I print from a list that have single ([) vs double ([[) brackets. For example, the output with double brackets is different than with single bracket when using the same python code.

my_movies = [['How I Met your Mother', 'Friends', 'sillicon valley','The Wire','breakin bad',
'Family Guy','Game of Throne','South park', 'Rick and Morty']]

my_movies = ['How I Met your Mother', 'Friends', 'sillicon valley','The Wire','breakin bad',
'Family Guy','Game of Throne','South park', 'Rick and Morty']

for movies in my_movies: 
    for movie in movies:
        char_num=len(movie)
        print (movie)

Question: How does the single vs double bracket changes the list?

The list inside a list is called a nested list. In the following list my_movies_1 , you have length 1 for my_movies_1 and the length of the inner list is 9. This inner list is accessed using my_movies_1[0] .

my_movies_1 = [['How I Met your Mother', 'Friends', 'sillicon valley','The Wire','breakin bad', 'Family Guy','Game of Throne','South park', 'Rick and Morty']]

On the other hand, the following list is not a nested list and has a length of 9

my_movies_2 = ['How I Met your Mother', 'Friends', 'sillicon valley','The Wire','breakin bad','Family Guy','Game of Throne','South park', 'Rick and Morty']

How are they related :

Here my_movies_1[0] would give you my_movies_2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM