Reading about Python? Actually practice it. Try PyChallenge free

Python Tutorial

Python lists

Python hosting: PythonAnywhere — host, run and code Python in the cloud. Free tier available.

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:
Practice Python with interactive exercises

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

BackNext

Practice
Stop reading. Start writing Python.
PyChallenge gives you interactive exercises in your browser — no install needed.
Practice Python with interactive exercises