How to Understand List and Arrays in Python

Lists and Arrays in Python and their differences.

Table of contents

  1. Differences between List and Array
  2. Working with Lists
    1. Creating List
    2. Appending List
    3. List with Heterogeneous data

Differences between List and Array

S.No.Python ListsPython arrays
1List is mutable. You can change data.Array is mutable. You can change data
2List can have different types of data (it can have Heterogeneous data)Array can have only one type of data
3List can have different types of data (it can have Heterogeneous data)Array is an ordered collection of data
4List can have different types of data (it can have Heterogeneous data)Array is fixed. It can’t grow and shrink.
Python list vs arrays

Working with Lists

Creating List

Here’s is logic how to create a List.

mylist = [] # empty list is created
mylist.append(1) # append() function is used to add elements into list
mylist.append(2)
mylist.append(3)
print(mylist[0]) # prints 1
print(mylist[1]) # prints 2
print(mylist[2]) # prints 3
# prints out 1,2,3
for x in mylist: # for loop is used
print(x)
12 Python Interview Questions
12 Python Interview Questions

Appending List

Various operation that you can do on Lists.

Python Code to Create List
List operations

Output

Python List Result
Output

List with Heterogeneous data

List supports heterogeneous data.

list1 = ['physics', 'chemistry', 2018, 2019]; # It has both numeric and strings
list2 = [1, 2, 3, 4, 5, 6, 7]; # It has only numeric values
print ("list1[0]: ", list1[0])
print ("list2[1:3]: ", list2[1:3])

Example:

In the below example you can find both numeric and Strings.

Python Logic With Different Data-types
List heterogeneous data

Output

Python List Output When it has Different type of data
Output

References

Related

Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.