Skip to main content

Python Lists


In this tutorial you will learn:

  • Python List
  • Adding elements to a List
  • Accessing elements of a List
  • Removing elements from a List

Python List

In the previous tutorials we learned about Number and String data types, now we will dive into one of the most important data type called List. List generally mean recording information in linear format and in a logical order and they do exactly the same in Python. List data type in python is immutable so it can be changed. In Python List can contain other data types within it and this feature makes it a lot useful. Another important feature of List is that they are dynamic and so there is no need to predefine its length. Declaring a list is simple.

For example:

  1. emptyList = [] #declares a List<br />
  2. numberList = [4, 8 ,10] #declares a List of numbers<br />
  3. mixedList = [“Python”, 2, 4.334, “Test”] #contains mixed data types

Adding elements to a List

Putting elements in a List is simple. In order to put elements in a List we use a function called append().

  1. dataList = []<br />
  2. dataList.append("Testing")
  3. dataList.append(66)
  4. dataList.append("Python")
  5. dataList.append(5.33)
  6. print(dataList) #prints ['Testing', 66, 'Python', 5.33]

Accessing elements of a List

In order to access elements of List we can simple put the index number in brackets or we can simply slice the List, just like strings. Remember that index always start with 0 and element at index 0 is always the first element.

  1. print("second element", dataList[1])
  2. print("second and third element", dataList[2:4])
  3. print(dataList)

Removing elements from a List

In order to remove elements from a list we need to use the del command. We ca use it by providing single index or by providing a range of indexes.

  1. del dataList[0]
  2. del dataList[2:4]
  3. print(dataList) #output [66, “Python”]

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.