What is a list?
Lists in python are one of the most basic data structures that is used to store data. Lists are created using square brackets '[ ]' and can contain any type of object. The list is a sequence of objects and can be accessed by their index number which starts at 0 and increases sequentially for each item in the list.
Lists are mutable. Creating lists in Python is easy and straightforward. All you need to do is type the list name followed by a set of square brackets [ ] and then enter the list items between braces, all separated by commas.
The following examples of syntax show how to create a list :
list1 = [] # empty listlist2 = [1, 2, 3,4] # list of integers list3 =[1.1, 2.2, 3.3, 4.4] # list of floats list4 = ['a, 'b', 'c', 'd'] # list of string
list5 = ['a', 1, 2.1] # list of mixed data types
Python provides a wide range of functions that can be used with lists such as sorting, deleting, adding elements to the list etc.
List Indexing :
List indexing is one of the most fundamental concepts in Python. It is used to access the elements of a list. We can use it to iterate over all elements in a list, and we can also use it to get or set an element at a specific position in the list. An index is the offset in a list of the first item in that list.
For example, if we have a list of students with their names and grades, then the index of the first name would be 0 and the grade would be 1.
myList = ['Alice', 96, 'Bob', 100]print(myList[1])
96
The syntax for using list indexing is:
list_name[index]
where “index” specifies which element we want from the list and “list_name” specifies which list we are referring to.
The following code snippet illustrates an error:
print(myList[6])IndexError: list index out of rangeThis Python error usually happens when an invalid index is used to access a list.
List Slicing :
List slicing is a powerful way to extract portions of a list. This technique enables programmers to extract an arbitrary number of items from a list and store them as a new list. It is an efficient way to process the data in a list and save it as a new list. It is an easy way to extract portions of lists without having to write complex for loops.
List slicing can be done by using the colon operator (:) which will extract the items from the start index up till and including the end index.
For example, consider the following list:my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
To extract a portion of this list, you can use list slicing. Here are a few examples:
Extracting a subset of elements:
subset = my_list[2:6] print(subset)
Output: [3, 4, 5, 6]In this example, the slice my_list[2:6] extracts elements from index 2 to index 5 (exclusive). The resulting subset contains elements [3, 4, 5, 6].
Extracting elements from the beginning of the list: