How to Create List in Python

How to Create List in Python – We can create a list in python in many ways. In this tutorial we will discuss the ways of creating a list in python.

Lists are just like dynamically sized arrays, declared in other languages (vector in C++ and ArrayList in Java). Lists need not be homogeneous always which makes it the most powerful tool in Python. A single list may contain DataTypes like Integers, Strings, as well as Objects. Lists are mutable, and hence, they can be altered even after their creation.

List in Python are ordered and have a definite count. The elements in a list are indexed according to a definite sequence and the indexing of a list is done with 0 being the first index. Each element in the list has its definite place in the list, which allows duplicating of elements in the list, with each element having its own distinct place and credibility.

The Python lists are widely used in python. Lists are one of the most used data structures in Python. It’s an unordered data store. In this article, we will learn how to work with lists in Python. You should know Python syntax and what is the lists in python. We have talked in a previous article, about the python dictionary data structure.

The lists are a sequential data store. Item saved in the list by its index. The list index starts with 0. This mean that a simple list  x = [1, 2, 3]. To get the 1st item you will need the item by index. This might be confusing. Don’t worry we will explain. Let’s start with

Table of Contents

Create a list in Python

To define lists in Python there are two ways. The first is to add your items between two square brackets.

Example:

items = [1, 2, 3, 4]

The 2nd method is to call the Python list built-in function by passing the items to it.

Example:

Items  = list(1, 2,3,4)

In both cases, the output will be

[1, 2, 3, 4]

The list can accept any data type. You can have a list of integers and strings. List in python doesn’t enforce to have a single item type in it. You can have a list of different items.

[1, 'name', {"key" : "value"}, list(1, 2, 3)]

This gives you the flexibility to add multiple data types in the list. You can add a list inside this list. This is called a nested list. Now we store our data into a python list it’s time to know how to do more with these data.

Append items to the list in Python

The list is a mutable data structure. This means you can create a list and edit it. You can add, insert, delete items to the created list. To add items to the list you can use the function and passing the value you want to add. The append function will add the item at the end of the list. The function lets you insert data in the place you want on the list. It’ll take two parameters, the index, and the value. Let’s see an example:

items = ["mobile", "laptop", "headset"]

# append the keyboard item to the list 
items.append("keyboard")
print(items)

# output
['mobile', 'laptop', 'headset', 'keyboard']


# insert the mouse item to the list in before the laptop item
items.insert(1, "mouse")
print(items)

# output
['mobile', 'mouse', 'laptop', 'headset', 'keyboard']

Sort lists in Python

We mentioned above that the Python list is unordered. The list is stored in memory like this. You can see a detailed implementation of the Python list here.

how to work with lists in python

This means that to access the value in item inside the list you have to call it by its index. More simply if we have student’s name list `students = [“John”, “Jack”, “Christine”]` and you want to get the name of the 1st student. You will need to know the index of this student’s name. In our case, it’s the zero index. The syntax will be student[0]

Let’s see a real-world example to understands it clearly.

Students = ["John", "Jack", "Christine"]
for i in Students:
    print(Students [i])

# Output
John
Jack
Christine

The list has unordered items. To sort them you can make use of the built-in python function sorted(). It’ll go through the list items and sort them.

The usage of the sorted() function is very simple. You need to pass the list to the sorted function. It’ll return the sorted list and change the original list too.

Example:

x = [4, 5, 1, 8, 2]
print(sorted(x))

# output
[1, 2, 4, 5, 8]

The first question that will come to your mind is how it works? it can sort the integers. What about the other types of the data string, dictionaries..etc. The sort function is more dynamic in sorting. This means that you can pass the sorting mechanism you want the list to be sorted based on. The first argument we can pass it to the sort function is reverse.

Note:  The difference between sorted() and sort() The sort()  change the orginal list. The sorted() doesn’t change the orginal list. It’ll retun the new soted list.

Reverse lists in Python

The sort function can reverse the list order. Set the reverse key to True will make Python automatically reverse the list sort. Let’s see an example.https://041455129c2a952f95c4bdd653e6abc5.safeframe.googlesyndication.com/safeframe/1-0-38/html/container.html

chars = ["z", "y", "o", "b", "a"]
print(sorted(chars)) 

# output
['a', 'b', 'o', 'y', 'z'] 

chars = ["z", "y", "o", "b", "a"]
print(sorted(chars, reverse=True)) 

# output
['z', 'y', 'o', 'b', 'a']

This example shows you how to reverse a list. In this example, we reverse the alphabetical order of the list.

Advanced sorting

You can add a customized sorting for the list by passing the sorting function in the key parameter.

chars = ["z", "y", "o", "b", "a"]
print(sorted(chars))

# output
['a', 'b', 'o', 'y', 'z']

words = ["aaaa", "a", "tttt", "aa"]
print(sorted(words, key=len))

# output
['a', 'aa', 'aaaa', 'tttt']


engineers = [
    {'name': 'Alan Turing', 'age': 25, 'salary': 10000},
    {'name': 'Sharon Lin', 'age': 30, 'salary': 8000},
    {'name': 'John Hopkins', 'age': 18, 'salary': 1000},
    {'name': 'Mikhail Tal', 'age': 40, 'salary': 15000},
]

# using custom function for sorting different types of data.
def get_engineer_age(engineers):
    return engineers.get('age')

engineers.sort(key=get_engineer_age)
print(engineers)

# output
[
    {'name': 'John Hopkins', 'age': 18, 'salary': 1000},
    {'name': 'Alan Turing', 'age': 25, 'salary': 10000},
    {'name': 'Sharon Lin', 'age': 30, 'salary': 8000},
    {'name': 'Mikhail Tal', 'age': 40, 'salary': 15000}
]

In the above examples, we used the key option to pass a sorting method to the sort function. The default one we used in chars array is sorting based on the order. In this list, the order was alphabetical. In the words list, we have a list of different words length. We want to sort it by the length of the word. The key we passed to the sort function is the built-in len() function. This will tell Python to sort the list based on the word length.

In the engineer’s example. This more likely to be an issue you need to solve in a more real-world example. You have a list of engineers data and you want to sort them based on the customized method. In our example, we sorted it by age.

Conclusion

As you might already know Python is an interpreted, high-level programming language for general-purpose programming. One of the areas where python stands out is its powerful standard library. The Python Library has tons of built-in functions to help you do extensive operations on lists without the need to code them yourselves.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x