Skip to main content

Working with Lists in Python

Lists in Python

Like an array, List is a collection of data (of different data types). Lists are specified using square brackets. 

Lists are very helpful when working with data in Python. Below are some of the features of Lists. 
  • Lists can hold data of different data types. 
  • Lists can be amended.
  • Data in the list can be accessed by using index.
  • Lists can hold duplicate data. 

In this post, we will see how to access, append or remove the data in Lists and how to use different list methods. 

Creating List in Python

Before we go on to different methods of lists, Let us see How to create a List in Python?

Like any other variable in python, List is created when the data is assigned with in square brackets. 

How to create a list in Python

In the above example, 'a_list' is created with the data and 'b_list' is created with no data. 

Accessing the data in a List

How to access the individual elements of Lists? Elements in the Lists can be accessed using index. Index starts with '0' and incremented by '1'. 

Index of a List in Python

Elements of a List can be accessed from the last element with the negative index value. As we can see above, Index of last element would be '-1'. 

If we need to retrieve the second element ("TWO"), index '1' or '-4' needs to be mentioned within square brackets. 

E.g.: 

print(a_list[1]) #prints the second element of a list

print(a_list[-4]) #prints the fourth element from end of a list

Retrieve Index of an element

We have seen how to access the elements using an index, If we know the element and need to know the index, Method 'index()' would be helpful. One thing to note is, it always returns the first index if the element is present multiple times in the list. 

Retrieve index of an element in List - Python

In the above example, '2' is present twice in the list. But, only one index (first occurrence '1') will be returned.

Print list in Python

Adding data to a List

One of the features of a List is the data can be amended. Using append() method, we can add the data to a list. data that needs to be added is to be passed as a parameter to append() method. 

Add new data to a List in Python

In the above example, we are passing "FOUR" to the method 'append()'. This should be added towards end of the list. 

If we notice, "FOUR" is already present in the list. Python allows duplicate data in the list and "FOUR" should be added successfully and printed like the below. 

Print in Python

In the above example, we are only adding one element at a time. If we have another list that needs to be added, this needs to be done with in a loop to add all of these elements using append. What if the list have large number of elements? 

Method 'extend()' can be used to append one list to the other. This method accepts a list (that is to be added) as an argument.

Extend a List in Python

In the above example, data in b_list would be added to a_list. 

Print a list in Python

Removing data from a List

Data can be removed from a list by using remove() method. Similar to the append() method, data that is passed as a parameter would be removed from a List. 

Remove data from a list in Python

In this example, we have two entries with 'FOUR'. And, first occurrence would be deleted from a list. 

Print List in Python

Copy data from one List to other

Like copying data from one variable to other, copying one list to other becomes essential. 

Is copying data from one list to other as simple as copying data from one variable to other? 

Simple answer is 'No'. 

Copying List in Python

In the above example, 
  • Line - 3: 'b_list = a_list', a_list doesn't actually copied over to b_list. b_list would be referencing a_list and any changes to a_list or b_list would reflect for both these. 
  • Lines - 5 & 6: We are appending '6' to b_list and 'SEVEN' to a_list. 
  • Lines - 8 & 9: Both lists should print the same result. 
Print List in Python

To avoid this issue, using copy() method would help to copy the data from one list to other. Let's see how this works using the same example. 

Copy data from one list to other in Python

  • Line - 3: we are using 'a_list.copy()' to copy the data, copy() method doesn't require any arguments.
Print list in Python

One other way to do this is by using function list(). This can be to copy the data from a list, tuple or by passing the data directly. 

Using list function to copy data in Python

In the above example, Lines from 5 to 8 should work in the same way and create list with the data passed.

Clear data from a List

Clearing data from a list can be done using 'clear()' method. This method doesn't require any arguments to be passed and clears the referencing list. 

Clear data from a List in Python

Retrieve the number of occurrences of an element

We know that Python allows duplicate values in the list. If we need to know the number of occurrences of an element in a list, we can use method 'count()'. We need to pass the element value as an argument to this method.

Count the number of occurrences of an element in the list

In the above example, '2' is present '3' times. 

Count the number of occurrences of an element in a List

Retrieve & Delete the value by Index

In the beginning we have seen how to access the values in a list by using index. Let's say if we need to retrieve the value by index and delete this from the list, 'pop()' method is helpful for doing this. 
  • 'pop()' accepts index as an argument and it returns the value in the specific index. 
  • Once the value is deleted, Python would automatically adjust the index, value in the next position would now be referred with this index. 
Retrieve & Delete the value from a list using pop() in Python

In the above example,
  • Line - 4: value '2' (at index 1) should be returned and deleted from the list.
  • Line - 5: value '3' would now be at index '1' and should be returned and deleted from the list.
Print list in Python

Sorting a List

Lists doesn't necessarily hold the data in the order (ascending or descending). But, if we need to sort the data in a list, Method 'sort()' is useful. With default parameters, this method sorts the data in ascending order and by passing 'reverse=True' data is updated in reverse order. And, method reverse() is useful to sort the data in reverse order.

Sort a list in Python



In the above example, 
  • Line-3: With no arguments passed, list would be sorted in ascending order.
  • Line-8: with 'reverse=True', list would be sorted in descending order. passing 'reverse=False' would work like default and data is sorted in reverse order.
  • Line-14: Data would be sorted in reverse order of index.
Print list in Python

One thing to note here is, sort() would only work with data of same data type in a list. If there are different data types present (like int and str), sort() would fail.

The above 'sort()' method updates the same list. If we need to sort the data and move it to the new list (and leave the original as is), we can use the function 'sorted()'. This accepts a list as an argument and returns sorted list. There is an optional parameter 'reverse', by passing 'True' to this parameter would sort the data in descending order.

Sorted() in Python


Print list in Python

Hope the above details were a bit of help to you in understanding more about Lists in Python.


If you have any Suggestions or Feedback, Please leave a comment below or use Contact Form.

Comments

Popular posts from this blog

All about READ in RPGLE & Why we use it with SETLL/SETGT?

READ READ is one of the most used Opcodes in RPGLE. As the name suggests main purpose of this Opcode is to read a record from Database file. What are the different READ Opcodes? To list, Below are the five Opcodes.  READ - Read a Record READC - Read Next Changed Record READE - Read Equal Key Record READP - Read Prior Record READPE - Read Prior Equal Record We will see more about each of these later in this article. Before that, We will see a bit about SETLL/SETGT .  SETLL (Set Lower Limit) SETLL accepts Key Fields or Relative Record Number (RRN) as Search Arguments and positions the file at the Corresponding Record (or Next Record if exact match isn't found).  SETGT (Set Greater Than) SETGT accepts Key Fields or Relative Record Number (RRN) as Search Arguments and positions the file at the Next Record (Greater Than the Key value). Syntax: SETLL SEARCH-ARGUMENTS/KEYFIELDS FILENAME SETGT  SEARCH-ARGUMENTS/KEYFIELDS FILENAME One of the below can be passed as Search Arguments. Key Fiel

What we need to know about CHAIN (RPGLE) & How is it different from READ?

CHAIN READ & CHAIN, These are one of the most used (& useful) Opcodes by any RPG developer. These Opcodes are used to read a record from file. So, What's the difference between CHAIN & READ?   CHAIN operation retrieves a record based on the Key specified. It's more like Retrieving Random record from a Database file based on the Key fields.  READ operation reads the record currently pointed to from a Database file. There are multiple Opcodes that start with READ and all are used to read a record but with slight difference. We will see more about different Opcodes and How they are different from each other (and CHAIN) in another article. Few differences to note.  CHAIN requires Key fields to read a record where as READ would read the record currently pointed to (SETLL or SETGT are used to point a Record).  If there are multiple records with the same Key data, CHAIN would return the same record every time. READE can be used to read all the records with the specified Ke

Extract a portion of a Date/Time/Timestamp in RPGLE - IBM i

%SUBDT Extracting Year, Month, Day, Hour, Minutes, Seconds or Milli seconds of a given Date/Time/Timestamp is required most of the times.  This can be extracted easily by using %SUBDT. BIF name looks more similar to %SUBST which is used to extract a portion of string by passing from and two positions of the original string. Instead, We would need to pass a value (i.e., Date, Time or Timestamp ) and Unit (i.e., *YEARS, *MONTHS, *DAYS, *HOURS, *MINUTES, *SECONDS or *MSECONDS) to %SUBDT.  Valid unit should be passed for the type of the value passed. Below are the valid values for each type. Date - *DAYS, *MONTHS, *YEARS Time - *HOURS, *MINUTES, *SECONDS Timestamp - *DAYS, *MONTHS, *YEARS, *HOURS, *MINUTES, *SECONDS, *MSECONDS Syntax: %SUBDT(value : unit { : digits { : decpos} }) Value and Unit are the mandatory arguments.  Digits and Decimal positions are optional and can only be used with *SECONDS for Timestamp. We can either pass the full form for the unit or use the short form. Below i