howtouselinux

5 Ways to Create a List in Python

Table of Contents

 

A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements. Each element or value that is inside of a list is called an item. Just as strings are defined as characters between quotes, lists are defined by having values between square brackets [ ].

A list can be defined as a collection of values or items of different types. The items in the list are separated with the comma (,) and enclosed with the square brackets [].

For example:
num = [1, 2, 3, 4]
letter = [‘a’, ‘b’, ‘c’, ‘d’]

List in Python

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 in Python with List function

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.

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 in Python with range function

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

 

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]

5 Useful Examples to use Python 3 Range Function

Create a List in Python with append method

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.

 

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

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

4 Ways to Append List in Python

Create a List in Python with list comprehension

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.

 

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]]

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn
Liquid Web Managed Word Press