Before we move any further, let’s first understand what we mean by lists in general. We have all heard of lists in our daily lives, whether it’s a list of household items handed to you by your mother or a list of your favourite Netflix shows.
Your mother, for example, will not give you the same list of products for purchasing, right? The same way a list acts in the Python programming language.
Oops! Shinchan’s mother is thrashing him because he bought the wrong items. Anyway, let’s take a deep dive into Lists in python.
Lists in python
Python lists are containers for storing values of any type. The most significant aspect of Python Lists is that they are mutable, which means that you can alter the elements of a list in place. Python will not create a new list when you change a member of a list.
A list is a standard data type of Python that can store a sequence of values belonging to any kind. Square brackets represent lists in Python.
For example, the following are some Python lists:
 # list with no member [1, 2, 3] # list of integers [1, 2.4, 3.8, 9] # list of numbers(integers and floating-point) ['a', 'b', 'c'] # list of characters ['a', 1, 'b', 3.9, 'zero'] # list of mixed value types ['One', 'Two', 'Three'] # list of strings
To create a list, put a number of expressions in square brackets. Use square brackets to indicate the start and end of the list and separate the items by commas. Lists can contain values of mixed data types, as shown in the above examples. Thus to create a list, you can write in the way shown below:
L =  L = [value, …]
This construct is known as a list display construct.
list1 = ['a', 'e', 'i', 'o', 'u']
Lists in python index their elements in two manners, i.e., forward indexing as 0, 1, 2, 3,… And backward indexing as -1, -2, -3, …
- List Elements’ two-way indexing
The figure above implies that the list’s elements can be accessed via two-way indexing, as seen below:
The individual elements of a list in python are accessed through their indexes. While accessing list elements, if you pass a negative index, Python adds the length of the list to the index to get the element’s forward index. That is, for a 6-element list L, L[-5] will be internally computed as L[-5+6] = L, and so on. This is how the backward indexing in lists works.
Now let’s take a look at creating lists from Existing Sequences
Creating an Empty List
The empty list is . It is the list equivalent of 0 or ‘. ‘ You can also create an empty list as shown below:
L = list()
It will generate an empty list and name that list as L.
Creating Lists from Existing Sequences
You can also use the built-in list type object to generate lists from sequences using the following syntax:
L = list( <sequence> )
Where <sequence> can be any kind of sequence object, including strings, tuples, and lists. Python creates the individual elements of the list from the individual elements of passed sequences. If you pass another list, the list function makes a copy of it.
Let’s understand it using some examples:
L1 = list('hello') print(L1)
['h', 'e', 'l', 'l', 'o']
List L1 is created from another sequence- a string “hello.” It generated individual elements from the individual letters of the string.
t = ('N', 'i', 'n', 'j', 'a') print("Tuple :", t) # Passing tuple t inside the list method L2 = list(t) print("List generated from tuple:", L2)
Tuple : ('N', 'i', 'n', 'j', 'a') List generated from tuple: ['N', 'i', 'n', 'j', 'a']
List L2 is created from another sequence- a tuple t. It generated individual elements of the passed tuple t.
Taking the input from the user
You can also use the conventional method of creating lists of single characters or single digits via keyboard input.
Consider the following code below:
# Taking input from the user list = list(input('Enter the list elements: \n')) print("Entered list elements: ", list)
Entered list elements: ['1', '2', '2', '5', '2', '0', '0', '1']
Notice, Even if we enter integral numbers, they are automatically converted to strings. To enter a list of integers through the keyboard, you can use the method given below.
Most commonly used method to input lists is int(input()) is shown below:
list =  n = int(input("Enter the no. of elements in list: \n")) # for in loop for taking the input one by one for i in range(n): element = int(input("Enter the next element \n")) # In-built function for adding the element at the last list.append(element) # Printing of Entered list print("Entered list is :", list)
Enter the no. of elements in list: 3 Enter the next element 23 Enter the next element 56 Enter the next element 98
Entered list is : [23, 56, 98]
Traversing a List
Traversing a series means accessing and processing each element of it. Thus, traversing a list means the same thing, and the mechanism for doing so is the same, namely, Python loops. That is why we sometimes refer to a traversal as looping over a sequence.
The for loop makes it simple to traverse or loop through the elements in a list, as shown below:
for <item> in <List>:
process each item here
For example, the following loop shows each item of a list L in separate lines:
L = ['C', 'o', 'd', 'i', 'n', 'g', 'Ninjas'] for c in L: # traversing over a list print(c, end=' ') print()
C o d i n g Ninjas
How does it work?
The loop variable c in the above loop will be assigned the List elements, one at a time. So, loop-variable c will be assigned to ‘C’ in the first iteration, and hence ‘C’ will be printed; in the second iteration, c will get element ‘o’ and ‘o’ element will be printed; and so on.
If you only need to use the indexes of elements to access them, you can use functions range() and len() like this:
for index in range(len(L)):
Process List[index] here
L = ['C', 'o', 'd', 'i', 'n', 'g', ' ', 'N', 'i', 'n', 'j', 'a', 's'] # len() to calculate the no. of elements length = len(L) # range() for specifying the length for i in range(length): print(L[i], end=' ') print()
C o d i n g N i n j a s
Now that you know about list traversal let’s learn about list operations.
The most frequent operations with lists are joining lists, replicating lists, and slicing lists. This is what we’ll be discussing in this part.
Joining two lists is as simple as adding two numbers. The concatenation operator + is the easiest way to do this.
Consider the example given below:
L1 = ['C', 'o', 'd', 'i', 'n', 'g'] L2 = ['N', 'i', 'n', 'j', 'a', 's'] # Joined two lists using "+" operator L3 = L1 + L2 print(L3) # OR print(L1 + L2)
['C', 'o', 'd', 'i', 'n', 'g', 'N', 'i', 'n', 'j', 'a', 's'] ['C', 'o', 'd', 'i', 'n', 'g', 'N', 'i', 'n', 'j', 'a', 's']
The ” + ” operator joins two lists to form a new one. As can be seen, the resultant list contains the first elements of the first list, followed by entries from the second. You can also combine two or more lists to create a new one.
When used with lists, the + operator requires that both operands be off the list type. A number or any other value cannot be added to a list. The following expression, for example, will result in an error:
list + number list + complex_number list + string
List1 = ['lol', 'lmao', 'loml', 'ikr'] print(List1 + 3) # Not a list type print(List1 + 'abc') # Not a list type
Traceback (most recent call last): File "C:\Users\CodingNinjas\PycharmProjects\pythonProject\main.py", line 2, in <module> print(List1 + 3) TypeError: can only concatenate list (not "int") to list
This code illustrates the above statements.
Replicating or Repeating lists
For repeating a list specified number of times, the * operator is used.
List1 = ['lol', 'lmao', 'loml', 'ikr'] # The * operator repeats a list specified no. of times and creates a new list print(List1 * 3)
['lol', 'lmao', 'loml', 'ikr', 'lol', 'lmao', 'loml', 'ikr', 'lol', 'lmao', 'loml', 'ikr']
When used with lists, the + operator requires both the operands as list-types; and the * operator requires a list and an integer.
Slicing the Lists
List slices are the subpart of a list extracted out. You can use indexes of list elements to create list slices as per the following format:
seq = L[start : stop]
The above statement will create a list slice, namely, seq, having elements of list L, on indexes, start, start+1, start+2,…, stop-1. The index on the last limit is not included in the list slice as the index starts from 0 like in arrays. The list slice is a list in itself; you can perform all operations on it.
Consider the following example:
list = [10, 12, 14, 20, 22, 24, 30, 32, 34] seq = list[3 : -3] print("BEFORE MODIFICATION: ", seq) # Trying to modify an element of seq in place seq = 'Ninja' print("AFTER MODIFICATION: ", seq)
BEFORE MODIFICATION: [20, 22, 24] AFTER MODIFICATION: [20, 'Ninja', 24]
If the resultant index for regular indexing is outside the list, Python throws an IndexError exception. Instead, slices are considered as borders, and the output simply contains all elements between the limits. Python just returns the elements that fall within specified bounds, if any, for a start and stop supplied beyond list limitations in a list slice, without raising any errors.
For example, consider the following:
list = [10, 12, 14, 20, 22, 24, 30, 32, 34] seq1 = list[3: 30] # Giving upper limit way beyond the size of the list print("Sequence 1: ", seq1) seq2 = list[-15: 7] # Giving lower limit much lower print("Sequence 2: ", seq2)
Sequence 1: [20, 22, 24, 30, 32, 34] Sequence 2: [10, 12, 14, 20, 22, 24, 30]
Here, what happens is, Python returns elements from the list falling in range 3 onwards < 30 for sequence 1. And for sequence 2, Python returns elements from list falling in range -15 forth < 7.
Lists can also be used to perform slicing steps. That is, if you wish to extract every other element of the list rather than consecutively, there is a way out – the slice steps.
Seq = L[start : stop : step]
L[start : stop : step] creates a list slice out of list L with elements falling between indexes start and stop, not including stop, skipping step-1 elements in between.
Consider the following example:
list = [10, 12, 14, 20, 22, 24, 30, 32, 34] seq = list[0: 10: 2] print(seq)
[10, 14, 22, 30, 34]
Now, it’s your turn, Ninja, to take another step.
Frequently asked questions
Lists in python are used to hold many things in a single variable. Lists are one of four built-in data types in Python; used to store data collections. The Other three are Tuple, Set, and Dictionary, all of which have various features and applications.
Lists are stored in memory as references, with a reference at each index rather than a single character because some objects are larger than others. Each item on the list is stored in a different location in memory.
The significant distinction between these two data types is the operations that are performed on them. Lists are used as containers for items with different data types, whereas arrays are used for elements with the same data type.
To recap the session, we covered the foundations of Python lists. We have also seen fundamental operations like traversing, concatenating, replicating, and slicing, which are helpful for a deeper comprehension of the Lists.
Don’t sit still. Practice the stated difficulties, and try to implement them on your own for greater comprehension.
Furthermore, you can refer to these fantastic articles to help you overcome the obstacles and become a stronger Python programmer: Python Keywords and Identifiers, Understanding Global Keyword in Python and Python Data Types.
Happy Learning Ninja!
By: Alisha Chhabra