Python

 

 

 

 

Python - List

 

List in Python is similar to an array in any other language, but it has much more methods (features) to handle elements (item) of the list.

 

A Python list is a built-in data structure that stores a mutable, ordered sequence of elements. Lists are versatile and can hold elements of different data types, including other lists, which makes them suitable for a wide range of applications. Since lists are mutable, their elements can be added, removed, or modified after the list is created.

 

To create a list, you can use square brackets [] and separate the elements with commas. An empty list can be created by using an empty pair of square brackets []. The elements in a list can be of any data type, such as integers, floats, strings, or even other lists and custom objects.

 

One of the main features of lists is that they are ordered, which means that the elements maintain their position within the list. You can access individual elements of a list using their index, starting with 0 for the first element, 1 for the second, and so on. Negative indices can be used to access elements from the end of the list, with -1 referring to the last element, -2 to the second last, and so on.

 

Python provides various built-in methods and functions to manipulate lists, such as:

  • len(): Returns the number of elements in the list.
  • append(): Adds an element to the end of the list.
  • extend(): Appends the elements of another iterable (such as another list) to the end of the list.
  • insert(): Inserts an element at a specified index.
  • remove(): Removes the first occurrence of an element from the list.
  • pop(): Removes and returns the element at a specified index or the last element if no index is provided.
  • index(): Returns the index of the first occurrence of an element in the list.
  • count(): Returns the number of occurrences of an element in the list.
  • sort(): Sorts the elements of the list in-place.
  • reverse(): Reverses the order of the elements in the list in-place.
  • copy(): Returns a shallow copy of the list.

 

 

 

Differences among Array, Set, Dictionary

 

Arrays, sets, and dictionaries are all collection data structures in Python, but they have some key differences in terms of their properties and use cases. Here's a summary of their main differences:

 

Arrays:

  • Arrays are a fixed-size, mutable, and ordered collection of elements, typically of the same data type.
  • Elements can be accessed and modified by their index, allowing for fast and efficient random access.
  • Arrays are not a built-in data structure in Python, but can be used through the array module or other libraries like NumPy.
  • Use cases: Arrays are suitable for situations where you need to store and manipulate elements of the same data type, especially when working with large amounts of numerical data or when you need to perform mathematical operations on the data.

 

Sets:

  • Sets are an unordered collection of unique, hashable elements.
  • Sets do not allow duplicate elements and do not support indexing or slicing.
  • Sets are mutable, and elements can be added or removed after the set is created.
  • Sets are a built-in data structure in Python and can be created using the set() constructor or curly braces {}.
  • Use cases: Sets are suitable for situations where you need to store unique elements, perform membership tests, or carry out mathematical set operations such as unions, intersections, and differences.

 

Dictionaries:

  • Dictionaries store key-value pairs in an unordered collection.
  • Keys must be unique and hashable, while values can be of any data type.
  • Dictionaries are mutable, and key-value pairs can be added, removed, or updated after the dictionary is created.
  • Dictionaries are a built-in data structure in Python and can be created using curly braces {} or the dict() constructor.
  • Use cases: Dictionaries are suitable for situations where you need to store and manipulate data based on keys, such as storing configuration settings, counting word frequencies, or implementing caching mechanisms.

 

 

 

Example

 

Followings are examples showing various operations and usage of lists.

 

NOTE 1 : All the examples in this page are written in Python 3.x. It may not work if you use Pyton 2.x

NOTE 2 : All the examples in this page are assumed to be written/run on Windows 7 unless specifically mentioned. You MAY (or may not) need to modify the syntax a little bit if you are running on other operating system.

  • Creating a List : Empty List - Example 1
  • Creating a List : Numeric Items - Example 2
  • Creating a List : String Items - Example 3
  • Creating a List : 2D List - Example 4
  • Getting the length (size) of a List - Example 5
  • Accessing a List : Getting one item - Example 6
  • Accessing a List : Getting item from 2D List - Example 7
  • Accessing a List : Getting a block of items - Example 8
  • Accessing a List : Getting items in interval - Example 9
  • Accessing a List : Getting every other items - Example 10
  • Accessing a List : Looping Through a List : for - Example 11
  • Member check in a List - Example 12
  • Going through every items in 2D List - Example 13  
  • Going through every items in 2D List with irregular row size - Example 14  

 

Examples :

 

< Example 1 >

 

aList = []

print(aList)

 

Result :----------------------------------

[]

 

 

< Example 2 >

 

aList = [1, 2, 3, 4, 5]

print(aList)

 

Result :----------------------------------

[1, 2, 3, 4, 5]

 

 

< Example 3 >

 

aList = ["Item1","Item2","Item3"]

bList = ['Item1','Item2','Item3']

print(aList)

print(bList)

 

Result :----------------------------------

['Item1', 'Item2', 'Item3']

['Item1', 'Item2', 'Item3']

 

 

< Example 4 >

 

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

print(aList2D)

 

Result :----------------------------------

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

 

 

< Example 5 >

 

aList = [1,2,3]

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

print(len(aList))

print(len(aList2D))

print(len(aList2D[0]))

 

Result :----------------------------------

3

2

3

 

 

< Example 6 >

 

aList = ["Item1","Item2","Item3"]

print(aList[2],aList[1],aList[0])

 

Result :----------------------------------

Item3 Item2 Item1

 

 

< Example 7 >

 

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

print(len(aList2D[0]))

print(len(aList2D[0][1]))

 

Result :----------------------------------

[1,2,3]

2

 

 

< Example 8 >

 

aList = [0,1,2,3,4,5,6,7,8,9]

print(aList[2:6])

 

Result :----------------------------------

[2, 3, 4, 5]

 

 

< Example 9 >

 

 

aList = [0,1,2,3,4,5,6,7,8,9]

print(aList[2:8:2])  # syntax is aList[start:stop:step]

 

Result :----------------------------------

[2, 4, 6]

 

 

< Example 10 >

 

aList = [0,1,2,3,4,5,6,7,8,9]

print(aList[::2])  

print(aList[2::2])

 

Result :----------------------------------

[0, 2, 4, 6, 8]

[2, 4, 6, 8]

 

 

< Example 11 >

 

aList = [0,1,2,3,4,5,6,7,8,9]

 

for i in aList :

   print("current i =",i)

 

Result :------------------------------------

 

current i = 0

current i = 1

current i = 2

current i = 3

current i = 4

current i = 5

current i = 6

current i = 7

current i = 8

current i = 9

 

 

< Example 12 >

 

fruits = ["Apple","BlueBerry","Banana","SrawBerry"]

 

print("'Apple' in fruits = ",("Apple" in fruits))

print("'Bean' in fruits = ",("Bean" in fruits))

 

 

Result :------------------------------------

 

'Apple' in fruits =  True

'Bean' in fruits =  False

 

 

< Example 13 >

 

aList2D = [

           [11,12,13],

           [21,22,23],

           [31,32,33]

           ];

 

// To do this, you need to specify row/col size

print("======================")  

print("[")

for r in range(0,3) :

    print("[",end='')

    for c in range(0,3) :

        print(aList2D[r][c],end='')

        print(" ",end='')

    print("]")

print("]")

 

// To do this, you do not need to specify row/col size

print("======================")

print("[")

for r in aList2D :

    print("[",end='')

    for c in r :

        print(c,end='')

        print(" ",end='')

    print("]")

print("]")

 

 

Result :------------------------------------

 

======================

[

[11 12 13 ]

[21 22 23 ]

[31 32 33 ]

]

======================

[

[11 12 13 ]

[21 22 23 ]

[31 32 33 ]

]

 

 

 

< Example 14 >

 

aList2D = [

           [11,12],

           [21,22,23,24,25],

           [31,32,33]

           ];

 

print("======================")

print("[")

for r in aList2D :

    print("[",end='')

    for c in r :

        print(c,end='')

        print(" ",end='')

    print("]")

print("]")

 

 

Result :------------------------------------

 

======================

[

[11 12 ]

[21 22 23 24 25 ]

[31 32 33 ]

]

 

 

< Example 15 >