What Is a List and How to Split the Elements of a List?

How to split the elements of a list?

Lists are one of the most frequently used data structures in the Python language. They are used to store different data types together.

Let us see what is a list, ways to create a list, how to access the list elements, and finally, splitting the elements of the list.

What Is a List?

A list is a Python data structure that can store elements of different data types in a single variable or a single storage area. The main difference between a list and an array is that a list can contain heterogeneous elements while the array can’t.

The elements of a list are enclosed within square brackets.

Let us see an example of a simple list.

#exampleofalist
lis=['1','2','3','Apple','Banana','Orange']
print("The elements of the list:\n",lis)

In the second line, we have created a variable called lis to store the elements. All the elements are enclosed within square brackets and separated by a comma.

In the next line, we print the list with the help of print() function. The \n is a newline character and creates a new line for the text after it.

The output is given below.

Example of a List
Example of a List

Now that we have understood the structure of a list, let us see the characteristics of a list.

Characteristics of a List

  • Every element in the list has an index. The indexing starts at 0.
  • The list elements have a certain order that cannot be changed.
  • Lists are mutable, which means that after the creation of a list, its elements can be changed or modified.
  • Lists also allow for duplicate elements.
  • Lists are often confused with one other data structure of Python which is a tuple.

Refer to this article to know more about Tuples.

Let us see the differences between a list and a tuple.

CategoryListTuple
Syntax The list elements are enclosed within square brackets[]The elements of the tuple are enclosed within parentheses()
MutabilityElements of a list can be modified after the creationTuples are immutable which means that once created, the elements cannot be changed or modified
Dynamic/StaticLists are dynamic in natureTuples are static
PerformanceLists are a bit slowerTuples are faster to work with because of their static nature
Memory ConsumptionLists take up more memoryTuples consume less memory compared to lists
Differences between Lists and Tuples

How to create a list?

There are multiple ways to create a list.

In this post, we are going to look at the following approaches.

  • Creating a list with the help of []
  • Creating an empty list and appending the elements one by one
  • Using the list() constructor

Creating a List With the Help of []

This method is a common and easy way to create a list.

All the elements we want to be on our list are enclosed within the square brackets[].

Let us see an example of this method.

#with the help of []
Grocerylist=['1','Apple','2','Banana','3','Orange','4','Watermelon']
print(Grocerylist)

In the above example, we have created a new variable called Grocerylist to store the list elements.

In the next line, we are printing this list using the print function.

List With []
List With []

Creating an Empty List and Appending the Elements One by One

In this method, we are going to create an empty list with the help of [] and use the append() function to append the new elements to the empty list.

Let us see how we can do that.

#creating an empty list and appending the elements
#emptylist
mylist=[]
mylist.append("Apple")
mylist.append("Banana")
mylist.append("Orange")
mylist.append("Grapes")
print(mylist)
mylist.sort()
print("Sorted list:",mylist)

Firstly, we have created an empty list called mylist by just giving the square brackets and nothing between them.

Then in lines 4-7(Highlighted code), we used the append() function to add a few elements to the empty list.

If you observe the order of the appended elements, they are not alphabetically arranged. Therefore, we used the sort() function to arrange them according to the precedence of the first letter of the word.

The output is as follows.

Appending Elements To The Empty List
Appending Elements To The Empty List

Using the list() Constructor

Now that we have seen the easiest ways to create a list, why use a separate constructor to create a list, when we can just create one without it?

You are right. We don’t need the list() constructor if we are creating a list directly.

But we might need the help of this constructor while creating the list from other data structures.

For example, we might use the list() constructor if we are creating a list from a dictionary or a set.

Check out this article to know about the other approaches to converting a dictionary to a list.

#creating a dictionary
dict={'a':1,'ab':2,'abc':3,'abcd':4,'abcde':5,'abcdef':6}
print(dict)

We have created a dictionary called dict to store the elements in the form of ‘key’:value pairs.

In the next line, we are printing the dictionary.

The dictionary is given below.

Dictionary
Dictionary

Let us see how we can convert this dictionary into a list.

#using the list() constructor
lis=list(dict)
print(lis)

In the above code snippet, we have created a new variable called lis to store the list items. We have used the list() constructor and passed the above-created dictionary as an argument to it.

The newly created list is as shown.

Creation Of List Using The list()
Creation Of List Using The list()

One important thing to remember while creating a list from a dictionary is that the keys of the dictionary will be the items of the list.

How to Access the List Elements?

These are the following methods we are going to use to access the elements of a list.

  • Using the [] with the position
  • Using the slice ‘:’ operator
  • Using the in operator to check if the element is in the list

Using the [] With the Position of the Required Element

We can use the [] operator and specify the position of the element we wish to retrieve from the list.

Let us see how we can do that with an example.

#accessing the list elements
#using []operator
lis=['Red','Blue','Green','Yellow','Orange','Purple','Violet']
print(lis)

We are creating a list of colors and storing them in a variable called lis.

Next, we are printing this list using the print function.

Accessing The Elements With []
Accessing The Elements With []

Let us print the elements in the First and Second positions. Remember, in python indexing starts from zero. So the first and second elements are Blue and Green.

#accessing Blue and Green
print(lis[1])
print(lis[2])

And the output is given below.

Blue And Green
Blue And Green

Using the Slice ‘:’ Operator

We can also use the colon which is also called the slice operator to access multiple elements from a list.

Let us see the slicing operation for the same example.

#print Yellow,Orange,Purple
lis=['Red','Blue','Green','Yellow','Orange','Purple','Violet']
print(lis[3:7])

The element at the third position is ‘Yellow’ and the element at the sixth position is ‘Violet’. In order to access the last element, we need to give the next number of the last index. So if you want to access the element at the sixth position, the number should be 7.

The output is as shown.

Slicing
Slicing

Using the in constructor to Check if the Element is in the List

The in operator can be used to check if a certain element is present in the list or not. If the element is in the list, it returns true. Else, it returns False.

Let us check with two colors – Yellow and Cyan.

Since Yellow is on the list, the in operator returns True.

But the color Cyan is not on the list. Hence, it returns False.

print(lis)
if 'Yellow' in lis:
  print("True")
else:
  print("False")
if 'Cyan' in lis:
  print("True")
else:
  print("False")

The output is given below.

The In Operator
The In Operator

How to Split the Elements of a List?

Splitting the elements of a list can be useful in many situations. You might want to work with only a certain element or a set of elements of a list.

Splitting the elements of a list can help us work with the data in more flexible and powerful ways, depending on the problem we are trying to solve.

There are many approaches to splitting the elements. We are going to see the following approaches.

  • Using the split() method
  • Using for loop
  • Splitting the list into chunks of size n

Using the split() Method

We can use the split() function to separate the elements into a subset of our own choice.

Let us see how we can use this method.

#using the split()
newlist=['1','2','3','4','5','6']
print(newlist)

For the above example, we have created a variable called newlist to store a list of numbers from 1 through 6.

In the next line, we are printing this list.

The output is given below.

Newlist
Newlist

Let us see how we can split this list into single entities.

lis=[]
for i in newlist:
    lis.append(i.split())
print(lis)

In the first line, we have created an empty list called lis to store the list elements after splitting,

We have created a for loop to run through each element in the original list. Then, we are using the iterator variable i to split the list into single entities.

Next, these single elements are appended to the new empty list we created earlier.

The separated list is printed with the help of the print function.

Separated List
Separated List

Using the For Loop

Let us take the same list we have taken in the creation of list example-Grocerylist

Let us see how we can split the elements using for loop.

The code is given below.

Grocerylist=['1','Apple','2','Banana','3','Orange','4','Watermelon']
print("The length of the list is:")
print(len(Grocerylist))
print("The list elements are:")
for i in range(len(Grocerylist)):
    print(Grocerylist[i])

Let us see what we did in the above code.

Firstly, we created a list to store the elements in a variable called Grocerylist.

Next, we try to check the length of the list we created using the len function.

In the next line, we are printing the length. As you may have guessed already, the length of our list is 8 which means, there are 8 items in our list.

print("The list elements are:") : We are printing a statement to understand that the next few lines in the output are going to be the elements of the list.

In the next line, we are using a for loop to iterate through each element of the list and print the elements each in a new line.

for i in range(len(Grocerylist)): Observe what we did here. To iterate for loop through any item, we use the range function. The range function tells the loop where to start and where to stop the process.

Now the range doesn’t accept any other data type other than an integer. So instead of the above line, if we have used for i in range(Grocerylist), it would return an error. Hence, in such cases where the iterable object is not an integer data type, we use the length of the object to iterate through its items.

Splitting the list using For loop
Splitting the list using For loop

Using the numpy.array_split() to Split the List into chunks of size n

The numpy.array_split is used to split the array into new arrays, divided by a size specified by the user.

We are going to use this method to split a list.

The code is given below.

import numpy as np
newlist=['Variable','Constant','Model','Learning',"Hello World", "Machine Learning", "Supervised Learning"]
print("The list is:")
print(newlist)
my_arrays = np.array_split(newlist, 3)
# print the resulting arrays
for arr in my_arrays:
    print(arr)

In the first line, we are importing the NumPy library that is used to call the function we are using.

In the following line, we are creating a variable called newlist which has a combination of character and string elements.

In the next line, we are printing the list.

Next, we are creating an array called my_arrays to store the elements after splitting. The size we have specified is 3, which means, the array is divided into three different arrays.

We are using a for loop to iterate through the array and used an iterator variable called arr to print the separated arrays.

The new arrays are given below.

Splitting the List Using Numpy
Splitting the List Using Numpy

As you can see from the above code, there are seven elements in the list we created. But, we have specified the number of chunks to be 3. So, the seven elements are divided into three different lists of distinct sizes.

Conclusion

To summarize, we have seen what is a list and also an example of a simple list.
We have seen the characteristics of Python Lists and the differences between lists and tuples.
We have seen various ways to create a list such as using the square brackets to create a list and print the list, creating an empty list, and appending the elements one by one to the empty list. Finally, we have seen the creation of the list from a dictionary from a special constructor list ().
In this approach, we have observed that a dictionary’s keys become the list elements.

Next, we explored the different approaches to accessing the elements of the list.
We have discussed accessing an element by specifying the position of the element we want to retrieve.
In the following approach, we have seen the usage of the slicing operator to access multiple elements at a time.
We have seen a small trick to access the last element of the list, giving the next number of the element’s index after the slice operator.
In the last approach, we observed the usage of the in constructor to check if the element is present in the list.
This operator returns True if the element we are trying to access is present in the list. Else, it returns False.

In splitting the elements of a list, we have seen three methods.
In the first approach, we learned how to use the split() method to separate the list elements into single entities.
We have used the for loop to split the elements using the range function which only accepts integer data types. Hence, we have seen the usage of the len function that returns the length of the list which is an integer.
In the last approach, we learned about the Numpy library’s special function np.array_split() which allows us to split the list into n different-sized arrays where n can be of our choice.

References

To know more about the list and its inbuilt functions, refer to the official Python Documentation.

Refer to the Numpy manual to know more about the numpy.array_split() function.