Tuesday 17 September 2019

Python Lists

In Python, list is one of the basic data structure useful to store multiple data items. 

  • Python list is the compound data types which can be used to group values
  • List is a kind of collections in Python. 
  • The list can be written as a list of comma-separated values (items) between square brackets
  • Lists might contain items with different data types. Let’s use Python’s List.

Creating a Python's List


Following example will create a list of characters, numbers and words.

# List of characters

>>> myList = ['a', 'b', 'c', 'd', 'e']
>>> myList
['a', 'b', 'c', 'd', 'e']

# List of numbers

>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]

# List of words

>>> insurance = ['sbi', 'hdfc', 'icici', 'lic']
>>> insurance
['sbi', 'hdfc', 'icici', 'lic']


Accessing values from a List


Elements of List can be used by referring it's index number. For example, to print first value from list - insurance, use following code:

>>> insurance[0]
'sbi'

>>> print(insurance[0])
sbi


Like strings, lists can also be indexed and sliced:

# index 0 returns the first item
>>> squares = [1, 4, 9, 16, 25]
>>> squares[0]
1

# index -1 returns the last item
>>> squares[-1]
25

# slicing returns a new list
>>> squares[-4:]
[4, 9, 16, 25]

All slice operations return a new list containing the requested elements. This means that the following slice returns a new (shallow) copy of the list:

>>> squares[:]
[1, 4, 9, 16, 25]

Lists also support operations like concatenation:

>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Lists are a mutable type; hence it is possible to change content of list. Check the following examples:


# something's wrong in following code; cube of 4 is not 65; let's change it.

>>> cubes = [1, 8, 27, 65, 125]
>>> cubes[3] = 64  # replace the wrong value
>>> cubes
[1, 8, 27, 64, 125]
* * * * *


No comments:

Post a Comment