1

so whats the difference between:

x = [1,1,1], [1,1,1], [1,1,1], [1,1,1] 

and

x = [[1,1,1], [1,1,1], [1,1,1], [1,1,1]] 

do the square brackets around the second option do anything?

3
  • 3
    First one will create a tuple of lists, second one will create a list of lists. Commented Jul 14, 2015 at 10:04
  • 3
    @AvinashRaj both examples work Commented Jul 14, 2015 at 10:04
  • 2
    Did you try printing both to see what you had? Commented Jul 14, 2015 at 10:09

4 Answers 4

7
x = [1,1,1], [1,1,1], [1,1,1], [1,1,1] 

Will create a tuple with lists

x = [[1,1,1], [1,1,1], [1,1,1], [1,1,1]] 

Will create lists of list

i.e.)

x = [1,1,1], [1,1,1], [1,1,1], [1,1,1] x ([1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]) type(x) <type 'tuple'> "a","b" ('a', 'b') 
Sign up to request clarification or add additional context in comments.

Comments

2

The first one creates a tuple of lists , while the second one creates a list of lists.

tuples are immutable, whereas lists are mutable.

Example for 1st one -

>>> x = [1,1,1], [1,1,1], [1,1,1], [1,1,1] >>> x ([1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]) >>> x[0] = 1 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment 

Example for 2nd one -

>>> x = [[1,1,1], [1,1,1], [1,1,1], [1,1,1]] >>> x [[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]] >>> x[0] = 1 >>> x [1, [1, 1, 1], [1, 1, 1], [1, 1, 1]] 

Comments

2

Without the brackets it is a tuple:

>>> x = [1,1,1], [1,1,1], [1,1,1], [1,1,1] >>> x ([1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]) >>> type(x) <type 'tuple'> 

You can't modify the items in a tuple.

With [] is it a list:

>>> x = [[1,1,1], [1,1,1], [1,1,1], [1,1,1]] >>> x [[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]] >>> type(x) <type 'list'> 

Comments

2

The first one is the same as doing this :

x = ([1,1,1], [1,1,1], [1,1,1], [1,1,1])

This is a tuple of lists.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.