Python lists are one of the most versatile data types that allow us to work with multiple elements at once. For example, Show
Create Python ListsIn Python, a list is created by placing elements inside square brackets [], separated by commas. # list of integers my_list = [1, 2, 3]A list can have any number of items and they may be of different types (integer, float, string, etc.). # empty list my_list = [] # list with mixed data types my_list = [1, "Hello", 3.4]A list can also have another list as an item. This is called a nested list. # nested list my_list = ["mouse", [8, 4, 6], ['a']]Access List ElementsThere are various ways in which we can access the elements of a list. List IndexWe can use the index operator [] to access an item in a list. In Python, indices start at 0. So, a list having 5 elements will have an index from 0 to 4. Trying to access indexes other than these will raise an IndexError. The index must be an integer. We can't use float or other types, this will result in TypeError. Nested lists are accessed using nested indexing. my_list = ['p', 'r', 'o', 'b', 'e'] # first item print(my_list[0]) # p # third item print(my_list[2]) # o # fifth item print(my_list[4]) # e # Nested List n_list = ["Happy", [2, 0, 1, 5]] # Nested indexing print(n_list[0][1]) print(n_list[1][3]) # Error! Only integer can be used for indexing print(my_list[4.0])Output p o e a 5 Traceback (most recent call last): File "<string>", line 21, in <module> TypeError: list indices must be integers or slices, not floatNegative indexingPython allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on. # Negative indexing in lists my_list = ['p','r','o','b','e'] # last item print(my_list[-1]) # fifth last item print(my_list[-5])Output e p List indexing in PythonList Slicing in PythonWe can access a range of items in a list by using the slicing operator :. # List slicing in Python my_list = ['p','r','o','g','r','a','m','i','z'] # elements from index 2 to index 4 print(my_list[2:5]) # elements from index 5 to end print(my_list[5:]) # elements beginning to end print(my_list[:])Output ['o', 'g', 'r'] ['a', 'm', 'i', 'z'] ['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z']Note: When we slice lists, the start index is inclusive but the end index is exclusive. For example, my_list[2: 5] returns a list with elements at index 2, 3 and 4, but not 5. Add/Change List ElementsLists are mutable, meaning their elements can be changed unlike string or tuple. We can use the assignment operator = to change an item or a range of items. # Correcting mistake values in a list odd = [2, 4, 6, 8] # change the 1st item odd[0] = 1 print(odd) # change 2nd to 4th items odd[1:4] = [3, 5, 7] print(odd)Output [1, 4, 6, 8] [1, 3, 5, 7]We can add one item to a list using the append() method or add several items using the extend() method. # Appending and Extending lists in Python odd = [1, 3, 5] odd.append(7) print(odd) odd.extend([9, 11, 13]) print(odd)Output [1, 3, 5, 7] [1, 3, 5, 7, 9, 11, 13]We can also use + operator to combine two lists. This is also called concatenation. The * operator repeats a list for the given number of times. # Concatenating and repeating lists odd = [1, 3, 5] print(odd + [9, 7, 5]) print(["re"] * 3)Output [1, 3, 5, 9, 7, 5] ['re', 're', 're']Furthermore, we can insert one item at a desired location by using the method insert() or insert multiple items by squeezing it into an empty slice of a list. # Demonstration of list insert() method odd = [1, 9] odd.insert(1,3) print(odd) odd[2:2] = [5, 7] print(odd)Output [1, 3, 9] [1, 3, 5, 7, 9]Delete List ElementsWe can delete one or more items from a list using the Python del statement. It can even delete the list entirely. # Deleting list items my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm'] # delete one item del my_list[2] print(my_list) # delete multiple items del my_list[1:5] print(my_list) # delete the entire list del my_list # Error: List not defined print(my_list)Output ['p', 'r', 'b', 'l', 'e', 'm'] ['p', 'm'] Traceback (most recent call last): File "<string>", line 18, in <module> NameError: name 'my_list' is not definedWe can use remove() to remove the given item or pop() to remove an item at the given index. The pop() method removes and returns the last item if the index is not provided. This helps us implement lists as stacks (first in, last out data structure). And, if we have to empty the whole list, we can use the clear() method. my_list = ['p','r','o','b','l','e','m'] my_list.remove('p') # Output: ['r', 'o', 'b', 'l', 'e', 'm'] print(my_list) # Output: 'o' print(my_list.pop(1)) # Output: ['r', 'b', 'l', 'e', 'm'] print(my_list) # Output: 'm' print(my_list.pop()) # Output: ['r', 'b', 'l', 'e'] print(my_list) my_list.clear() # Output: [] print(my_list)Output Finally, we can also delete items in a list by assigning an empty list to a slice of elements. >>> my_list = ['p','r','o','b','l','e','m'] >>> my_list[2:3] = [] >>> my_list ['p', 'r', 'b', 'l', 'e', 'm'] >>> my_list[2:5] = [] >>> my_list ['p', 'r', 'm']Python List MethodsPython has many useful list methods that makes it really easy to work with lists. Here are some of the commonly used list methods.
List Comprehension: Elegant way to create ListsList comprehension is an elegant and concise way to create a new list from an existing list in Python. A list comprehension consists of an expression followed by for statement inside square brackets. Here is an example to make a list with each item being increasing power of 2. pow2 = [2 ** x for x in range(10)] print(pow2)Output [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]This code is equivalent to: pow2 = [] for x in range(10): pow2.append(2 ** x)A list comprehension can optionally contain more for or if statements. An optional if statement can filter out items for the new list. Here are some examples. >>> pow2 = [2 ** x for x in range(10) if x > 5] >>> pow2 [64, 128, 256, 512] >>> odd = [x for x in range(20) if x % 2 == 1] >>> odd [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] >>> [x+y for x in ['Python ','C '] for y in ['Language','Programming']] ['Python Language', 'Python Programming', 'C Language', 'C Programming']Visit Python list comprehension to learn more. Other List Operations in PythonList Membership TestWe can test if an item exists in a list or not, using the keyword in. my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm'] # Output: True print('p' in my_list) # Output: False print('a' in my_list) # Output: True print('c' not in my_list)Output True False TrueIterating Through a ListUsing a for loop we can iterate through each item in a list. for fruit in ['apple','banana','mango']: print("I like",fruit)Output I like apple I like banana I like mango
If you are using Quantopian, it is advisable that you become familiar with numpy and pandas. For example: >>> import numpy as np >>> -1*np.arange(20) array([ 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19])Then you will have a[1]==-1, a[5]==-5, etc. Python lists can be indexed in a variety of ways, including positive and negative numbers. This article will discuss how to use the “-” minus parameter to access specific elements in a list. Basic List Structure and OperationsA list is defined using square brackets and elements within them. Each element is separated with the help of a comma. Syntax: list_name = [element_!, element_2, ..., element_n] Code: int_list= [3, 4, 5, 5, 6] # a list containing all integers char_list = ['a', 'b', 'c', 'd'] # al list of characters str_list = ["apple", 'banana', 'lemon', 'orange'] # a list of strings What Are List Indexes?Indexing is the fundamental unit of any linear data structure in any programming language. For every computer, the default index started from 0 and goes on till n-1. Here n denotes the total number of elements in the respective data structure. Types are:
These help us to access the individual elements of this data structure. Let us see the operations in the next section. Negative Indexes in ListsThis is the main point of focus on our topic. The “-1” parameter in lists is to denote the Python interpreter that operations are from the last element. First, we shall see how we can access the elements using the index numbers. Indexing In ListsUsing Negative Indexes to Retrieve List Datamy_list = [45, 5, 33, 1, -9, 8, 76] print(my_list[-1]) print(my_list[-2]) print(my_list[-3]) Output: Reversing the List With Negative IndexUsing built-in function “reverse()”: my_list = [45, 5, 33, 1, -9, 8, 76] my_list.reverse() Output: [76, 8, -9, 1, 33, 5, 45] Reversing the list using -1 my_list = [45, 5, 33, 1, -9, 8, 76] my_list[::-1] Output: [76, 8, -9, 1, 33, 5, 45] # reversed list Removing Elements With Negative IndexUsing the pop() function and giving -1 as parameter inside it we can remove the last element of that list and we get a new list. my_list = [45, 5, 33, 1, -9, 8, 76] my_list.pop(-1) my_list Output: 76 # popped out element [45, 5, 33, 1, -9, 8] # new list returned Advantages of Using Negative Indexing in Python List
ConclusionThis concludes our tutorial on Python negative indexing. We hope you found it helpful! If you have any questions or comments, please feel free to share them below. Thanks for reading! |