How to create a list in Python

By: On:

In this Python tutorial, we will discuss what is a python list and different ways to create a list in Python. Also, we will discuss:

  • Create a list in python with size
  • Create list of size n
  • How to create a list from a string in Python
  • Python convert a list to space-separated string
  • Creates a list of lists in Python,
  • Python creates a list from dictionaries
  • How to create a list of floats
  • Create a list in python using a range
  • Create a list using for loop
  • Python create list of first n integers
  • Creates a list of objects
  • Convert array to list python
  • Average of a list python
  • Python sort list of lists
  • Randomly select an item from list python
  • Python apply function to a list
  • Python permutations of a list
  • Python permutations of list items of a given length
  • Python combinations of a list
  • Python combinations with replacement
  • How to repeat in python

What is a python list

  • The Group of elements is called a list in python.
  • Python lists are very similar to an array but the main difference is, an array can store only one type of element whereas, a list can store different types of elements.
  • List are mutable (changeable).
  • Lists are dynamics which means size is not fixed. Lists are represented using a square bracket[ ], separated by commas.

Example:


x = ['Lists',6.3,2.2,12,32]
print(x)

After writing the above code (python list), Ones you will print “x” then the output will appear as a “[‘List’,6.3,2.2,12,32]”. You can refer to the below screenshot for creating a List with different data types.

Create list in python
python list

Create a list in python with size

Here, We will see how to create a python list with a fixed size. I have initialized the element array with some size.

Example:

size = [0]*5
print(size)

After writing the above code (list in python with size), Ones you will print “size” then the output will appear as a “[0, 0, 0, 0, 0]”. Here, I have initialized it with [0] and my fixed-size value is 5. You can refer to the below screenshot for creating a List with a fixed size.


Create a List with fixed size in python
Create a list in python with size

Python create list of size n

To create a list of size n declare the variable with the size.

Example:

n = 8
store = [2]*n
print(store)

After writing the above code (list of size n), Ones you will print “store” then the output will appear as a “[2,2,2,2,2,2,2,2]”. You can refer to the below screenshot for creating a List with size n.

Python create list of size n
Python create list of size n

Python create a list from a string

For creating a list from a string we have the split() method, Which will create a list separated with commas in a square bracket.

Example:

value = "Welcome to Python"
print(value.split())

After writing the above code (create a list from a string), Ones you will print “value.split()” then the output will appear as a “[‘Welcome’, ‘to’, ‘Python’]” which is a list. You can refer to the below screenshot for creating a List from a string.

create a list from a string in python
Python create a list from a string

Python convert a list to space-separated string

In Python, by using join() method we can convert a list to a space – separated string.

Example:

color = ['Black','Red','Blue']
val = ' '.join(color)
print(val)

After writing the above code (convert a list to space-separated string), Ones you will print “value” then the output will appear as a “Black, Red, Blue”. You can refer to the below screenshot for converting the list to a space-separated string.

convert list to space separated string python
convert a list to space-separated string in python

Python creates a list of lists

To create a list in python we need to use .append method to create a list of lists.

Example:

l1=[101,102,103] 
l2=[104,105] 
listoflists= []
listoflists.append(l1) 
listoflists.append(l2) 
print("List of Lists:",listoflists)

After writing the above code (create a list of lists), Ones you will print “List of Lists:”, listoflists” then the output will appear as aLists of Lists: “[[101,102, 103], [104, 105]]“. You can refer to the below screenshot for creating a list of lists.

Python list of lists
Python creates a list of lists

Python creates a list from dictionaries

Dictionary is a collection of key-value pairs in Python. Dictionary is mutable(changeable). It is represented by curly braces “{}” separated by commas. Whereas, colon “:” separates each key from its value.

Example:

snames = {'Ram': 11, 'Rohan': 12, 'Shyam':13, 'Jai': 14}
mylist = [(k,v) for k,v in snames.items()]
print(f"mylist : {mylist}")

After writing the above code (create a list from dictionary), Ones you will print (f”mylist: {mylist}”) then the output will appear as a [(‘Ram’, 11), (‘Rohan’, 12), (‘Shyam’, 13), (‘Jai’, 14)]. You can refer to the below screenshot for creating a list from the dictionary.

create list from dictionary in python
creates a list from dictionaries in python

Python create list of floats

For creating a list of floats in python, we need a for loop to iterate throughout the list. Also, use the append for creating a new list.

Example:

my_val = ["1.1", "3.5", "7.6"]
list_of_floats = []
for item in my_val:
list_of_floats.append(float(item))
print(list_of_floats)

After writing the above code (create a list of floats), Ones you will print (list_of_floats) then the output will appear as a “[1.1, 3.5, 7.6]” as a float value. You can refer to the below screenshot for creating a list of floats.

List of float in python
Python create list of floats

Create a list in python using a range

We can use a range() for creating a list in python and a “*” operator for continuous value. To make a list in continuous we can give a range value, which has its start and end value.

Example:

value = [*range(110,116)]
print(value)

After writing the above code (create a list using a range), ones you will print “value” then the output will appear as “[110, 111, 112, 113, 114, 115]” as a list with continuous value. You can refer to the below screenshot for creating a list in python using a range.

Create a list in python using a range

Create a list in python using for loop

For creating a list in python using for loop we need to iterate over items in a list by using for loop.

Example:

marks = ['34', '55', '67', '88', '89']
list_of_int = []
for item in marks:
list_of_int.append(int(item))
print(list_of_int)

After writing the above code (create a list using for loop), ones you will print “list_of_int” then the output will appear as”[34, 55, 67, 88, 89]” as a list. You can refer to the below screenshot for creating a list in python using for loop.

Create a list in python using for loop
Create a list in python using for loop

Python create list of first n integers

For creating a list of first n integers in python, we will first declare the n and it will have the first n integer number as a list. By using range we can get the first n integer.

Example:

n = 5
p = list(range(5))
print(p)

After writing the above code (create a list of first n integers), ones you will print “p” then the output will appear as”[0,1,2,3,4]” as a list. You can refer to the below screenshot for creating a list of the first n integers in python.

create a list of first n integer in python

Python creates a list of objects

In python, a class is created in which an object is defined by the user and it can be a member of the list with different data types. For creating a list of objects in python we can use append for class instances to list.

Example:

class employee:
def __init__(self, empname, empid):
self.empname = empname
self.empid = empid
list = []
list.appened( employee('Rohan', 15) )
list.appened( employee('Ram', 30) )
list.appened( employee('Sohan', 34) )
for val in list:
print(val.empname, val.empid)

After writing the above code (create a list of objects), ones you will print “(val.empname, val.empid)” then the output will appear as”Rohan 15 Ram 30 Sohan 34” as a list. You can refer to the below screenshot for creating a list of objects in python.

Python creates a list of objects

Convert array to list python

In python, to convert array to list in python we can use the function ” tolist() ” which will convert the array into a list.

Example:

from array import*
def my_array(num_array):
my_list = num_array.tolist()
print(my_list)
num_array = array('i', [12,14,16,18,20])
my_array(num_array)

After writing the above code (convert array to list python), ones you will print then the output will appear as “ [12,14,16,18,20] ” as a list. Here, the function tolist() converts the array to list with the same element. You can refer to the below screenshot for converting an array to list python.

Convert array to list python

Average of a list python

In python, for doing an average of a list we can use the built-in function sum() and len(). The average is the sum of all the elements present in the list divided by the total number of elements.

Example:

my_list = [2, 4, 6, 8]
t = sum(my_list)
l = len(my_list)
average = t/l
print(average)

After writing the above code (average of a list python), ones you will print ” average ” then the output will appear as ” 5.0 “. Here, the function sum() will add all the elements, and the len() function will count the number of elements. You can refer to the below screenshot for the average of a list python.

Average of a list python

Python sort list of lists

In python, to sort list of lists we can use index of each inner list and sort the inner list by specified index as a key.

Example:

my_list = [[21, 'Y'], [18, 'X']]
list_to_sort = sorted(my_list, key=lambda a: a[1])
print(list_to_sort)

After writing the above code (python sort list of lists), ones you will print ” list_to_lists ” then the output will appear as ” [[18, ‘X’], [21, ‘Y’]] “. Here, sorted is used to sort the element, and the lambda a: a[1] is used to sort iterable by each element. You can refer to the below screenshot for the python sort list of lists.

Python sort list of lists

Randomly select an item from list python

In python, to get the randomly selected item from the list we will import the random module then we have to use the choice() function to select the item randomly from the list.

Example:

import random
name = ["tom", "alice", "sid", "zoe"]
print(random.choice(name))

After writing the above code (randomly select an item from list python), ones you will print ” random.choice() ” then the output will appear as ” alice “ as a random item from the list. Here, the function choice() will randomly return the items from the list. You can refer to the below screenshot for randomly select an item from the list python.

Randomly select an item from list python

Python apply function to a list

  • The apply function to a list, we will use a map().
  • Call map(func, *iterables) with a list as iterables for applying a function to each element in the list and it returns a map object.
  • Use list() to convert the map object to list.

Example:

my_list = ["x", "y", "z"]
map_obj = map(str.upper, my_list)
n_list = list(map_obj)
print(n_list)

After writing the above code (python apply function to a list), ones you will print ” n_list ” then the output will appear as ” [‘X’, ‘Y’, ‘Z’] “. Here, it requires applying certain functions to each element in the list so, we used capitalize characters. You can refer to the below screenshot python apply function to a list.

Python apply function to a list
Python apply function to a list

Python permutations of a list

In python, we can find the permutation of a list by directly using the method called itertools package. First, we need to import the itertools package to implement permutation in python. Permutation of a list is all the possible ordering of the elements in the list.

Example:

from itertools import permutations
my_permut = permutations([12, 13, 14])
for a in list(my_permut):
print(a)

After writing the above code (python permutations of a list), once you will print ” a ” then the output will appear as ” (12, 13, 14) (12, 14, 13) (13, 12, 14) (13, 14, 12), (14, 12, 13) (14, 13, 12) “. Here, the method takes a list as an input and returns an object list of tuples with all permutation. You can refer to the below screenshot python permutations of a list.

Python permutations of a list
Python permutations of a list

Python permutations of list items of a given length

To get the permutation of list items of a given length then, we need to specify the length in order to get all permutation of the list.

Example:

from itertools import permutations
my_permut = permutations([12, 13, 14], 2)
for a in list(my_permut):
print(a)

After writing the above code (python permutations of list items of a given length), once you will print ” a ” then the output will appear as ” (12, 13) (12, 14) (13, 12) (13, 14) (14, 12) (14, 13) “. Here, we specify the length as ” 2 “. So, if you want to get the permutation of length L then we can do like this. You can refer to the below screenshot python permutations of a list.

Python permutations of list items of a given length
Python permutations of list items of a given length

Python combinations of a list

In python, to find the combinations of a list we can use the method called itertools package. First, we need to import the itertools package to implement combinations in python. Combination of list are all possible grouping of items.

Example:

from itertools import combinations 
my_comb = combinations([12, 13, 14], 2)
for a in list(my_comb):
print(a)

After writing the above code (python combinations of a list), once you will print ” a ” then the output will appear as ” (12, 13) (12, 14) (13, 14) “. Here, this method takes a list and “r” as an input which will return object list of tuples with all possible combination. You can refer to the below screenshot python combinations of a list.

Python combinations of a list
Python combinations of a list

Python combinations with replacement

To get combination of same element with same element we will use combinations with replacement. Firstly we need to import combinations_with_replacement and then the element will be referred with the index value.

Example:

from itertools import combinations_with_replacement
my_comb = combination_with_replacement([12, 13, 14], 2)
for a in list(my_comb):
print(a)

After writing the above code (python combinations with replacement), once you will print ” a ” then the output will appear as ” (12, 12) (12, 13) (12, 14) (13, 13) (13, 14) (14, 14) “. Here, we have the combination of length ” 2 ” with replacement. Also, we have all possible subset arrangement of the iterators with repetition. You can refer to the below screenshot python combinations with replacement.

Python combinations with replacement
Python combinations with replacement

How to repeat in python

The itertools.repeat() falls under the infinite iterators and we will import itertools. Sometimes we need to repeat in program so, we can use repeat(val, num) where “val” is the value to be printed and “num” is number of times the data will be repeated.

Example:

import itertools 
print ("Print repeatedly the numbers: ")
print(list(itertools.repeat(123, 5)))

After writing the above code (how to repeat in python), once you will print ” (list(itertools.repeat(123, 5))) ” then the output will appear as ” [123, 123, 123, 123, 123] “. Here, we can see that the value “123” is repeatedly printed “5” times. You can refer to the below screenshot how to repeat in python.

How to repeat in python
How to repeat in python

You may like following Python tutorials:


Through this tutorial, we learned what is a list in Python? How to create a list in Python? How to create a list with size? create a list of size n, how to create a list from a string, Python convert a list to a space-separated string, how to creates a list of lists? Convert array to list python, Average of a list python, Python sort list of lists, Randomly select an item from list python, Python apply function to a list, Python permutations of a list, Python permutations of list items of a given length, Python combinations of a list, Python combinations with replacement and How to repeat in python.

How to creates a list from dictionaries in python? Python, create a list of floats, create a list in python using a range in python, create a list in python using for loop, create list of first n integers, and creates a list of objects.

Leave a Comment