what is difference between list and tuple in python?

The differences between tuples and lists is , tuples cannot be changed unlike lists. tuples use parentheses, whereas lists use square brackets.

Python list example

#!/usr/bin/python

#create an empty list
s = list()
for num in range(5):
	s.append(num)

#print items from list s
for item in s:
	print item

Run the code

bosch@bosch-Inspiron-N5050:~$ python sample.py 
0
1
2
3
4

Let us change the 3rd list object

#!/usr/bin/python

#create an empty list
s = list()
for num in range(5):
	s.append(num)

#chnage list objects
s[2]=10

#print items from list s
for item in s:
	print item


output

bosch@bosch-Inspiron-N5050:~$ python sample.py 
0
1
10
3
4

Python tuple example

#!/usr/bin/python

#create an empty tuple
s = tuple()
s = (1,2,'wiki')

#print items from tuple s
for item in s:
	print item

Output:

bosch@bosch-Inspiron-N5050:~$ python sample.py 
1
2
wiki
  • We cannot change tuple objects. for example below code would give error.
#!/usr/bin/python

#create an empty tuple
s = tuple()
s = (1,2,'wiki')

#cannot chnage tuple
s[0] = 5

#print items from tuple s
for item in s:
	print item
bosch@bosch-Inspiron-N5050:~$ python sample.py 
Traceback (most recent call last):
  File "sample.py", line 8, in <module>
    s[0] = 5
TypeError: 'tuple' object does not support item assignment

difference between list and tuple in python

  • List objects are mutable and thus they can’t be used as a key in the dictionary, while tuples can be used as key in dictionary.
tup    = (1,2)
li    = [1,2] 

e = {a: 1}     # OK
c = {b: 1}     # Error
  • List objects can be changed while tuples are not changed.
  • Lists are homogeneous while tuples are usually heterogeneous.
  • Lists are for variable length, tuples are for fixed length.

Ref:

http://stackoverflow.com/questions/626759/whats-the-difference-between-lists-and-tuples

https://docs.python.org/3/tutorial/datastructures.html




Related Contents to follow