Python lists


Lists is a sequence and a basic data structure.   A list may contain strings (text) and numbers.  A list is similar to an array in other programming languages, but has additional functionality.

Related Course:
Complete Python Bootcamp: Go from zero to hero in Python 3

Python List

We define lists with brackets []. To access the data, these same brackets are used.
Example list usage:

#!/usr/bin/python
 
l = [ "Drake", "Derp", "Derek", "Dominique" ]
 
print(l)     # prints all elements
print(l[0])  # print first element
print(l[1])  # prints second element

Add/remove

We can use the functions append() and remove() to manipulate the list.

#!/usr/bin/python
 
l = [ "Drake", "Derp", "Derek", "Dominique" ]
 
print(l)                # prints all elements
l.append("Victoria")   # add element.
print(l)                # print all elements
l.remove("Derp")       # remove element.
l.remove("Drake")      # remove element.
print(l)               # print all elements.

Sort list

We can sort the list using the sort() function.

#!/usr/bin/python
 
l = [ "Drake", "Derp", "Derek", "Dominique" ]
 
print(l)     # prints all elements
l.sort()    # sorts the list in alphabetical order
print(l)     # prints all elements

If you want to have the list in descending order, simply use the reverse() function.

#!/usr/bin/python
 
l = [ "Drake", "Derp", "Derek", "Dominique" ]
 
print(l)     # prints all elements
l.sort()    # sorts the list in alphabetical order
l.reverse() # reverse order.
print(l)     # prints all elements
Back
Next

34 thoughts on “Python lists

  1. Ben - August 27, 2015

    Hi,

    a=[]
     
    for i in range(1,10):
       if i%2 !=0:
          a.append[i]
    print a[0]

    But it showed : File “C:\Python27\learn\test.py”, line 48, in
    a.append[i]
    TypeError: ‘builtin_function_or_method’ object has no attribute ‘__getitem__’?

    why I can’t via loops to append value to a list?

    1. Frank - August 27, 2015

      Hi Ben, use brackets for append. Like this:

      #!/usr/bin/env python
       
      a=[]
       
      for i in range(1,10):
         if i%2 !=0:
            a.append(i)
       
      print(a[0])
      print(a)
  2. Ben - August 18, 2015
    a=['james','make','susan']
    print a.reseve();
     
    I expect the result is :['susan', 'make', 'james'] , but the it showed me like this :
    >>> 
    None
    james
    >>>

    Did anyone can tell me why

    1. Frank - August 18, 2015

      Hi Ben, this will work:

      >>> a=['james','make','susan']
      >>> a.reverse()
      >>> print a
      ['susan', 'make', 'james']

      This is because reverse() returns None (see the function call paragraph). The function call changes its internal list but does not return the new list.
      Some more examples:

      >>> a=[1,2,3]
      >>> print a.reverse()
      None
      >>> a
      [3, 2, 1]

      or

      >>> a=['james','make','susan']
      >>> print a.reverse()
      None
      >>> a
      ['susan', 'make', 'james']
      1. Ben - August 18, 2015

        Thank you so much . this function different from PHP/PERL

    2. Nagendra - August 21, 2015

      Hello ben,
      a.reverse function will perform the reverse operation, it will store in the variable,
      so call the variable then you got the answer ok
      Regards,
      Nagendra N

      1. Blooper - August 22, 2015

        I have a similar problem.
        I defined the variable first as n.
        When I command “print (n.sort())” or “print (n.reverse())” it responds “None” each time.

        1. Frank - August 22, 2015

          Call n.sort() or n.reverse() then print(n)

  3. Jonas - August 17, 2015

    When I type
    l = [ “Drake”, “Derp”, “Derek”, “Dominique” ]
    and
    print l
    it gives an error:
    SyntaxError: Missing parentheses in call to ‘print’

    1. Frank - August 17, 2015

      Hi, you are using Python 3.x. Use: print(l)

  4. Abhishek - August 11, 2015

    what is difference between list = [[0, 1], [1, 2], [2, 3]] and list = ([0, 1], [1, 2], [2, 3]) both appears to be array?

    1. Staff - August 11, 2015

      Good question! The second is a tuple, not a list. A tuple is a collection of variables that cannot be changed.
      Once you try to set one of the tuple variables, you will get an exception. Try with this code:

      #!/usr/bin/env python
       
      setA = [[0, 1], [1, 2], [2, 3]]
      setB = ([0, 1], [1, 2], [2, 3])
       
      print(setA)
      print(setB)
       
      setA[0] = [2,3]
      setB[0] = [2,3]
       
      print(setA)
      print(setB)
      1. Tinh Doan - September 16, 2015

        when I run this code on “http://pythonspot.com/run.php” both of them is the same??
        output is:
        [[0, 1], [1, 2], [2, 3]]
        ([0, 1], [1, 2], [2, 3])

        but when I run local, I get an error:
        TypeError: ‘tuple’ object does not support item assignment

        1. Frank - September 16, 2015

          The first one defines a list, the second one a tuple. Tuples cannot be given new values. You can read more on tuples here.

  5. Psk - July 18, 2015

    Can ya make a 2D and 3D array too?

    1. Frank - July 18, 2015

      Yes, there is no limit to the number of dimensions in an array.

      a 2d array:

      #!/usr/bin/env python3
       
      list = [[0, 1], [1, 2], [2, 3]]
       
      print(list)
      print(list[0][0])
      print(list[1][1])

      a 3d array:

      #!/usr/bin/env python3
       
      list = []
       
      for i in xrange(3):
          list.append([])
          for j in xrange(3):
              list[i].append(i+j)
       
      print(list)
      print(list[0][0])
      print(list[1][2])
      1. Bheesam Jangra - July 18, 2015

        when i am trying for this 3D array i am getting below error:
        Traceback (most recent call last):
        File “hello.py”, line 3, in
        for i in xrange(3):
        NameError: name ‘xrange’ is not defined

        i have python35-32 installed on my PC and when i am trying to run this i am getting above error.

        1. Frank - July 18, 2015

          Try changing to:

          #!/usr/bin/env python3
           
          list = []
           
          for i in range(3):
              list.append([])
              for j in range(3):
                  list[i].append(i+j)
           
          print(list)
          print(list[0][0])
          print(list[1][2])

          Also try:

          #!/usr/bin/env python3
           
          list = [[0, 1, 2], [1, 2, 3], [2, 3, 4]]
           
          print(list)
          print(list[0][0])
          print(list[1][1])
      2. Tinh Doan - September 16, 2015

        Why don’t use:

        list = [[0, 1, 4], [1, 2, 5], [2, 3, 6]]
        print(list)
        print(list[0][0])
        print(list[1][2])

        1. Frank - September 16, 2015

          That should work too, only difference is first one is dynamic second static. It depends on your application

  6. Hattem - June 8, 2015

    wow this is interest

Leave a Reply