Reputation: 49
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?
Upvotes: 1
Views: 124
Reputation: 8335
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')
Upvotes: 7
Reputation: 343
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.
Upvotes: 2
Reputation: 2592
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'>
Upvotes: 2
Reputation: 90889
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]]
Upvotes: 2