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

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

34 thoughts on “Python lists

  1. Articfox879 Gaming - August 12, 2017

    Just so you know the character before the = sign, is a L (lowercase), I spent 3 days before realizing this, so just helping some beginners out

  2. Ayesha - January 16, 2016

    How can i print the items in the list randomly

    1. Frank - January 24, 2016

      You can use the random.shuffle() method:

      #!/usr/bin/python
      import random
       
      list = [ "Drake", "Derp", "Derek", "Dominique" ]
      random.shuffle(list)
      print(list)
  3. José Chumán - December 8, 2015

    Is there any way to print like this without using any loop? I’m using Python 3.x

    l = [ “Drake”, “Derp”, “Derek”, “Dominique” ]
    Output:
    Drake
    Derp
    Derek
    Dominique
    1. Frank - December 8, 2015

      Loops are preferred but yes, you can print them one by one:

      l = ["Drake","Derp","Derek","Dominique"]
      print(l[0])
      print(l[1])
      print(l[2])
      print(l[3])

      There is another method, but loops would create the cleanest code.