howtouselinux

4 Ways to Create a List in Python

Table of Contents

Python is a versatile language that you can use for a variety of purposes. One of the things that Python is great for is creating lists. In this blog post, we will discuss 4 simple ways to create a list in Python.

We will also provide examples so that you can see how each method works. So, whether you are a beginner or an experienced Python user, you will be able to create lists using these methods!

List in Python

A list is a data structure that allows you to store multiple values in a single variable.

List variables are identified by square brackets, [] , and the values within the list are separated by commas. List elements can be any type of value, including other lists.

A list is created using square brackets [], with each item in the list being separated by commas:

[1, 2, 3]

This will create a list with three items: 1, 2 and 3. You can also create multi-dimensional lists:

[1, 2], [3, 4], [5, 6]

The list has the following characteristics:

  • The lists are ordered.
  • The element of the list can access by index.
  • The lists are the mutable type.
  • The lists are mutable types.
  • A list can store the number of various elements.

 

Create a List with List function in Python

Python list() function takes any iterable as a parameter and returns a list. In Python iterable is the object we can iterate over. Some examples of iterables are tuples, strings, and lists.

We can use this list function creates a list from an iterable object.

  • Syntax: list(iterable)
  • iterable: an object that could be a sequence (string, tuples) or collection (set, dictionary) or any iterator object.

 

Example:

string = “ABCDEF”
list = list(string)
print(list)
[‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’]

dict = {‘name’:”Eyong”,”age”:30,”gender”:”Male”} # define a dict
list2 = list(dict)
print(list2)
[‘name’, ‘age’, ‘gender’]

Converting a dictionary using list(dict) will extract all its keys and create a list. That is why we have the output [‘name’,’age’,’gender’] above. If we want to create a list of a dictionary’s values instead, we’ll have to access the values with dict.values().

Create a List with range function in Python

The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.In Python 3, we can combine the range function and list function to create a new list.

Range function Syntax

range(start, stop, step) – range() takes mainly three arguments having the same use in both definitions:

  • start – integer starting from which the sequence of integers is to be returned
  • stop – integer before which the sequence of integers is to be returned.
  • The range of integers ends at stop – 1.
  • step (Optional) – integer value which determines the increment between each integer in the sequence

 

Example: 
print(list(range(2, 4)))
# [2, 3]
print(list(range(2, 6)))
# [2, 3, 4, 5]
print(list(range(2, 10, 2)))
# [2, 4, 6, 8]
print(list(range(5,-1,-1)))
# [5, 4, 3, 2, 1, 0]

Create a List with append method in Python

The list append() method in Python adds a single item to the end of the existing list. We commonly use append() to add the first element to an empty list.

After appending to the list, the size of the list increases by one.

  • SYNTAX – list_name.append(item)
  • PARAMETERS – The append() method takes a single item as an input parameter and adds that to the end of the list.
  • Return Value – The append() method only modifies the original list. It doesn’t return any value as a return but will just modify the created list.

 

Example:
characters.append(‘Google’)
print(‘Updated list:’, characters)
Updated list: [‘Google’]

L = [‘red’, ‘green’, ‘blue’]
L.append(‘yellow’)
print(L)
[‘red’, ‘green’, ‘blue’, ‘yellow’]

Create a List with list comprehension in Python

List comprehension offers a shorter syntax when we want to create a new list based on the values of an existing list.

  • List comprehension is a sublime way to define and build lists with the help of existing lists.
  • In comparison to normal functions and loops, List comprehension is usually more compact and faster for creating lists.
  • However, we should always avoid writing very long list comprehensions in one line to confirm that code is user-friendly.
  • Remember, every list comprehension is rewritten in for loop, but every for loop can’t be rewritten within the kind of list comprehension.

 

Example:
separated_letters = [ letter for letter in ‘Google’ ]
print( separated_letters)
[‘G’, ‘o’, ‘o’, ‘g’, ‘l’, ‘e’]

even_list = [ i for i in range(10) if i % 2 == 0]
print(even_list)
[0, 2, 4, 6, 8]

new_list = [num * 2 for num in range(5)]
print(new_list)
[0, 2, 4, 6, 8]

list = [“even” if y%2==0 else “odd” for y in range(5)]
print(list)
[‘even’, ‘odd’, ‘even’, ‘odd’, ‘even’]

matrix = [[1, 2], [3,4], [5,6], [7,8]]
transpose_matrix = [[row[i] for row in matrix] for i in range(2)]
print (transpose_matrix)
[[1, 3, 5, 7], [2, 4, 6, 8]]

David Cao
David Cao

Hey there! I am David, a Cloud & DevOps Enthusiast and 18 years of experience as a Linux engineer. I work with AWS, Git & GitHub, Linux, Python, Ansible, and Bash. I am a technical blogger and a Software Engineer, enjoy sharing my learning and contributing to open-source.