Python Lists and Tuples

In all programming languages that we are quite familiar with, i.e, C, Java, C#, PHP,etc. have support for Arrays while the intelligent OOPs have ArrayList, an interesting feature. But is that all?

If the answer is NO. Let’s switch to Python, a language built with a certain positive vibe not to make a programmer’s life a purgatory. With Python, we have ease of code readability, 100 lines of code written in Java can be equivalent to 10 lines of meaningful Python code. And it’s opensource and reliable. The best part is that you can leave things on the framework and just work with what you need.

Coming to the topic, apart from arrays, Python provides several other quintessential data storage elements:

LISTS :

Lists are pretty much like ArrayLists. You can insert strings,variables,etc. in and out as you wish. Lets see some examples:

  • Open IDLE for Python 2.7. You can download it here.
  • First we create a list named Movies containing 3 movie names
    Movies=["Terminator 3","Titanic"]
    >>> print(Movies)
    ['Terminator 3', 'Titanic']
    
  • Now we’ll add another element to this List. This <listname>.append(object x) will insert object x at the end of the list.
    Movies.append("Avatar")
    >>> print(Movies)
    ['Terminator 3', 'Titanic', 'Avatar']
    >>> 
  • What if we want to insert in some other position?
    Movies.insert(1,"Psycho")
    >>> print(Movies)
    ['Terminator 3', 'Psycho', 'Titanic', 'Avatar']
  • We can even Sort the list.
    Movies.sort()
    >>> print(Movies)
    ['Avatar', 'Psycho', 'Terminator 3', 'Titanic']
  • We can remove an element too.
    Movies.remove("Psycho")
    >>> print(Movies)
    ['Avatar', 'Terminator 3', 'Titanic']

TUPLES :

Tuples can be categorized as Read-only Lists. A List is declared by [] whereas a tuple is denoted by (). Tuples are often very useful when we want a read-only archive.

  • Let’s create a Tuple first. Note that a single item tuple won’t be like (“Titanic”) rather like (“Titanic”,):
    Movies=("Titanic","Avatar")
    >>> print(Movies)
    ('Titanic', 'Avatar')