Lists, Tuples & Dictionary

Python Lists

Lists are very similar to arrays. They can contain any type of variable, and they can contain as many variables as you wish. Lists can also be iterated over in a very simple manner. A list contains items separated by commas and enclosed within square brackets ([]).

To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging to a list can be of different data type.

The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1.

The plus (+) sign is the list is concatenation operator, and the asterisk (*) is the repetition operator.

#!/usr/bin/python

list = [ 'abcd', 123 , 9.02, 'Rocky', 99.2 ]

tinylist = [123, 'Rocky']

print list          # Prints complete list

print list[0]       # Prints first element of the list
print list[1:3]     # Prints elements starting from 2nd till 3rd 
print list[2:]      # Prints elements starting from 3rd element

Repeat the list value using "*"

print tinylist * 2 # Prints list two times

Concatenate two list

print list + tinylist # Prints concatenated lists

Appending Lists

mylist = []

mylist.append(1)
mylist.append(2)
mylist.append(3)

print(mylist[0]) # prints 1
print(mylist[1]) # prints 2
print(mylist[2]) # prints 3

# prints out 1,2,3
for x in mylist:
    print x
Accessing an index which does not exist generates an exception (an error).
mylist = [1,2,3]
print(mylist[10])

Python Tuples

A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.

The main differences between lists and tuples are:

  • Lists are enclosed in brackets  "  [ ]  " and  their elements and size can be changed,
  • while tuples are enclosed in parentheses  "   ( )   " and cannot be updated.

Tuples can be thought of as read-only lists. 

#!/usr/bin/python

tuple = ( 'abcd', 123 , 9.02, 'Rocky', 99.2 )
tinytuple = (123, 'Rocky')

print tuple           # Prints complete list
print tuple[0]        # Prints first element of the list
print tuple[1:3]      # Prints elements starting from 2nd till 3rd 
print tuple[2:]       # Prints elements starting from 3rd element

print tinytuple * 2   # Prints list two times

print tuple + tinytuple # Prints concatenated lists

Result :- 

('abcd', 123, 9.02, 'Rocky', 99.2)
abcd
(13, 9.02)
(9.02, 'Rocky', 99.2)
(123, 'Rocky', 123, 'Rocky')
('abcd', 123, 9.02, 'Rocky', 99.2, 123, 'Rocky')

We cannot update Tuple as we already mentioned, Tuple is read-only

tuple[2] = 99   #This will give error, as we are trying to update tuple.

// List is different, list will replace the value to new value irrespectve of its type.

list[2] = 99

Python Dictionary

Python's dictionaries are kind of hash table. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.

Dictionaries are enclosed by curly braces ({ }) and values can be assigned/updated/replace and accessed using square braces ([]).

#!/usr/bin/python

mydict = {}
mydict['one'] = "This is one"
mydict[2]     = "This is two"

tinydict = {'name': 'Rocky','code':134, 'dept': 'support'}


print mydict['one']       # Prints value for 'one' key
print mydict[2]           # Prints value for 2 key
print tinydict            # Prints complete dictionary
print tinydict.keys()     # Prints all the keys
print tinydict.values()   # Prints all the values

  Alternatively, a dictionary can be initialized with the same values in the following notation:

#!/usr/bin/python

phonebook = {
    "John" : 938477566,
    "Jack" : 938377264,
    "Jill" : 947662781
}

Iterating over dictionaries

Dictionaries can be iterated over, just like a list. However, a dictionary, unlike a list, does not keep the order of the values stored in it. To iterate over key value pairs, use the following syntax:

for name, number in phonebook.iteritems():
    print "Phone number of %s is %d" % (name, number)

Removing a value

To remove a specified index, use either one of the following notations:

del phonebook["John"]

// or

phonebook.pop("John")

Loading ...

Related Results :

  1. Lists, Tuples & Dictionary
  2. Lists in Python
Note :
  • Related Posts are generally User Blog posts.
  • or Other tutorials from other networks of w3clan.com.
  • Any registered user can create related posts based on search term tags.

About the Author