Code Point
September 10, 2010, 06:58:13 AM *
Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length
News: Geshi Sintax Hilighting Mod Installed. Tens of languages available.
 
   Home   Help Search Login Register  
Pages: [1]   Go Down
  Print  
Author Topic: What is the difference between lists and tuples?  (Read 2283 times)
Cobra
Jr. Member
*

Karma: 0
Offline Offline

Posts: 3


« on: September 07, 2006, 10:47:33 PM »

What is the difference between lists and tuples?

Code
>>> a = (1, 2, 3)
>>> a
(1, 2, 3)
>>> b = [1, 2, 3]
>>> b
[1, 2, 3]

They look the same to me.
Logged
Alter Lobo
Global Moderator
Jr. Member
*****

Karma: 10
Offline Offline

Posts: 65


« Reply #1 on: September 07, 2006, 11:00:26 PM »

Lists, tuples and strings are sequences. All of them can be indexed.

Indexing a string:

Code
>>> s = 'abc'
>>> print s[0], s[1], s[2]
a b c

Indexing a tuple:

Code
>>> t = (1, 2, 3)
>>> print t[0], t[1], t[2]
1 2 3

The same with a list:

Code
>>> l = [1, 2, 3]
>>> print l[0], l[1], l[2]
1 2 3

Tuples and strings are immutable and lists are mutable. If I try to change a tuple or a string I get an error while I can do it with a list:

Code
>>> s[1]= 'x'
Traceback (most recent call last):
 File "<stdin>", line 1, in ?
TypeError: object does not support item assignment
>>>
>>> t[1] = 9
Traceback (most recent call last):
 File "<stdin>", line 1, in ?
TypeError: object does not support item assignment
>>>
>>> l[1] = 9
>>> l
[1, 9, 3]
Logged
Pages: [1]   Go Up
  Print  
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.11 | SMF © 2006-2009, Simple Machines LLC Valid XHTML 1.0! Valid CSS!