Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 274
ghv8 Avatar asked Oct 20 '25 03:10

ghv8


1 Answers

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

like image 52
Sheldore Avatar answered Oct 21 '25 16:10

Sheldore