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:
- emptyList = [] #declares a List<br />
- numberList = [4, 8 ,10] #declares a List of numbers<br />
- 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().
- dataList = []<br />
- dataList.append("Testing")
- dataList.append(66)
- dataList.append("Python")
- dataList.append(5.33)
- 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.
- print("second element", dataList[1])
- print("second and third element", dataList[2:4])
- 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.
- del dataList[0]
- del dataList[2:4]
- print(dataList) #output [66, “Python”]
Add new comment
- 318 views