paint-brush
Python 3: Concept of LIST in Detailsby@yogesh_ahdem
263 reads

Python 3: Concept of LIST in Details

by Yogesh RaghupatiJune 26th, 2020
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

The dictionary meaning of LIST is a number of connected items or names written or printed consecutively, typically one below the other. In python, the list is a mutable, or changeable, ordered sequence of elements where each element or value that is inside of a list is called an item. We can use indexing to change items within the list, by setting an index number equal to a different value. This gives us greater control over lists as we are able to modify and update the items that they contain.

People Mentioned

Mention Thumbnail

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - Python 3: Concept of LIST in Details
Yogesh Raghupati HackerNoon profile picture

The dictionary meaning of LIST is a number of connected items or names written or printed consecutively, typically one below the other.

In real world, lists are considered in many ways like playlist of songs, collection of your favourite videos, a list of user database and there are many more. But, if you are given a task about handling a list of users and filter out specific users under specific conditions then it becomes a tedious job to filter the list by going through each and every user. In such scenarios, programming comes into place to make your work easier.

So, now let us understand ‘What is a LIST?’ in python programming. In python, the list is a mutable, or changeable, ordered sequence of elements where each element or value that is inside of a list is called an item.

In string, how each value/element is represented as a character similarly in list, the each value/element is separated by comma where each element can be a string, variable or constants enclosed in [] bracket.

Syntax of List:

['LetsUpgrade', 'Batch1', B2, B3] Nested List: ['LetsUpgrade', ['java', 'python', 'c++'], 1, 2, ['B1', 'B2'], 'Exam']

Topics to be covered in LIST are as follows:

  • Indexing Lists
  • Lists are Mutable
  • Updating and Slicing Lists
  • Use of operators in List
  • Methods used in List
  • Built-in functions in List
  • Deleting Elements from List
  • Constructing a List with List Items
  • List and Strings
  • Parsing lines
  • Objects and values
  • Aliasing
  • List arguments
  • List Comprehensions
  • Using Conditionals with List Comprehensions
  • Nested Loops in a List Comprehension
  • Debugging

We are going understand the above topics through Examples not by theoretical…

#Indexing Lists:

Each item in a list corresponds to an index number, which is an integer value, starting with the index number 0.

For the list COURSES, the index breakdown looks like this:

The first item, the string 'Java' starts at index 0, and the list ends at index 4 with the item 'Javascript'.

print(COURSES[3])
OUTPUT:
R

If we call the list COURSES with an index number of any that is greater than 4, it will be out of range as it will not be valid:

print(COURSES[5])
Output:
IndexError: list index out of range

The above one was Positive Indexing and now let’s see Negative Indexing as shown below:

For the same list COURSES, the negative index breakdown looks like this

print(COURSES[-3])
1
2
	
Output
Python

#Lists are Mutable:

Example:-

>>> numbers = [17, 123]
>>> numbers[1] = 5
>>> print(numbers)
[17, 5]

Therefore, as per above example lists are changeable i.e mutable.

#Updating and Slicing Lists:

Updating

We can use indexing to change items within the list, by setting an index number equal to a different value. This gives us greater control over lists as we are able to modify and update the items that they contain.

If we want to change the string value of the item at index 1 from 'C++' to 'SQL', we can do so like this:

COURSES[1] = 'SQL'

Now when we print COURSES, the list will be different:

print(COURSES)
1
2
	
Output
['Java', 'SQL', 'Python', 'R', 'Javascript']

Similarly, it goes for Negative Indexing.

Slicing Lists

We can also call out a few items from the list. Let’s say we would like to just print the middle items of sea_creatures, we can do so by creating a slice. With slices, we can call multiple values by creating a range of index numbers separated by a colon [x:y]:

print(COURSES[1:4])
1
2
	
Output
['SQL', 'Python', 'R']

When creating a slice, as in [1:4], the first index number is where the slice starts (inclusive), and the second index number is where the slice ends (exclusive), which is why in our example above the items at position, 1, 2, and 3 are the items that print out.

If we want to include either end of the list, we can omit one of the numbers in the list[x:y] syntax.

print(COURSES[:3])
1
2
	
Output
['Java', 'SQL', 'Python']

This printed the beginning of the list, stopping right before index 3.

To include all the items at the end of a list, we would reverse the syntax:

print(COURSES[2:])
1
2
	
Output
['Python', 'R', 'Javascript']

We can also use negative index numbers when slicing lists, just like with positive index numbers:

print(COURSES[-4:-2])
print(COURSES[-3:])
1
2
3
	
Output
['SQL', 'Python']
['Python', 'R', 'Javascript']

One last parameter that we can use with slicing is called stride, which refers to how many items to move forward after the first item is retrieved from the list. So far, we have omitted the stride parameter, and Python defaults to the stride of 1, so that every item between two index numbers is retrieved.

The syntax for this construction is list[x:y:z], with z referring to stride. Let’s make a larger list, then slice it, and give the stride a value of 2:

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
 
print(numbers[1:11:2])
1
2
	
Output
[1, 3, 5, 7, 9]

Our construction numbers[1:11:2] prints the values between index numbers inclusive of 1 and exclusive of 11, then the stride value of 2 tells the program to print out only every other item.

We can omit the first two parameters and use stride alone as a parameter with the syntax list[::z]:

print(numbers[::3])
1
2
	
Output
[0, 3, 6, 9, 12]

By printing out the list numbers with the stride set to 3, only every third item is printed:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12

Slicing lists with both positive and negative index numbers and indicating stride provides us with the control to manipulate lists and receive the output we’re trying to achieve.

#Use of operators in List:

Operators are used for modifications in lists. We’ll be using the + and * operators and their compound forms += and *=.

The + operator can be used to concatenate two or more lists together:

LetsUpgrade_Courses = ['Java', 'ML', 'AI', 'Data Science', 'Javascript']
prizes= ['Hp Laptop', 'LED TV', 'Iphone']
 
print(LetsUpgrade_Courses + prizes)
Output
['Java', 'ML', 'AI', 'Data Science', 'Javascript','Hp Laptop', 'LED TV', 'Iphone']

Now, let’s look at * operator:

print(LetsUpgrade_Courses * 2)
print(prizes* 3)
Output
['Java', 'ML', 'AI', 'Data Science', 'Javascript','Java', 'ML', 'AI', 'Data Science', 'Javascript']
['Hp Laptop', 'LED TV', 'Iphone','Hp Laptop', 'LED TV', 'Iphone','Hp Laptop', 'LED TV', 'Iphone']

Compound forms '+= ‘ & ‘ *= ‘ :

for x in range(1,4):
    LetsUpgrade_Courses += ['AI']
    print(LetsUpgrade_Courses)
Output
['Java', 'ML', 'AI', 'Data Science', 'Javascript', 'AI']
['Java', 'ML', 'AI', 'Data Science', 'Javascript', 'AI', 'AI']
['Java', 'ML', 'AI', 'Data Science', 'Javascript', 'AI', 'AI', 'AI']
prizes = ['bike']
 
for x in range(1,4):
    prizes *= 2
    print(prizes)
	
Output
['bike', 'bike']
['bike', 'bike', 'bike', 'bike']
['bike', 'bike', 'bike', 'bike', 'bike', 'bike', 'bike', 'bike']

#Methods used in List:

Now, your work is to GOOGLE the below functions and understand how they work in Python Programming. (Exercise)

  • Append(): Add an element to the end of the list
  • Extend(): Add all elements of a list to the another list
  • Insert(): Insert an item at the defined index
  • Remove(): Removes an item from the list
  • Pop(): Removes and returns an element at the given index
  • Clear(): Removes all items from the list
  • Index(): Returns the index of the first matched item
  • Count(): Returns the count of number of items passed as an argument
  • Sort(): Sort items in a list in ascending order
  • Reverse(): Reverse the order of items in the list
  • copy(): Returns a copy of the list

#Built-in functions in List:

  • reduce(): Apply a particular function passed in its argument to all of the list
    elements stores the intermediate result and only returns the final
    summation value
  • sum(): Sums up the numbers in the list
  • ord(): Returns an integer representing the Unicode code point of the given Unicode character
  • cmp(): This function returns 1, if first list is “greater” than second list
  • max(): return maximum element of given list
  • min(): return minimum element of given list
  • all(): Returns true if all element are true or if list is empty
  • any(): return true if any element of the list is true. if list is empty, return false
  • len(): Returns length of the list or size of the list
  • enumerate(): Returns enumerate object of list
  • accumulate(): apply a particular function passed in its argument to all of the list elements returns a list containing the intermediate results
  • filter(): tests if each element of a list true or not
  • map(): returns a list of the results after applying the given function to each item of a given iterable
  • lambda(): This function can have any number of arguments but only one expression, which is evaluated and returned.

#Deleting Elements from List:

To remove the item, we’ll use the del statement then call the list variable and the index number of that item:

LetsUpgrade_Courses =['Java', 'ML', 'AI', 'Data Science', 'Javascript']
 
del LetsUpgrade_Courses[2]
print(LetsUpgrade_Courses)
Output
['Java', 'ML', 'Data Science', 'Javascript']

To remove more than one element, you can use del with a slice index:

>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> del t[1:5]
>>> print(t)
['a', 'f']

There are several other ways to delete elements from a list. If you know the index of the element you want, you can use pop and remove:

>>> t = ['a', 'b', 'c']
>>> x = t.pop(1)
>>> print(t)
['a', 'c']
>>> print(x)
b

pop modifies the list and returns the element that was removed. If you don’t provide an index, it deletes and returns the last element.

If you know the element you want to remove (but not the index), you can use remove:

>>> t = ['a', 'b', 'c']
>>> t.remove('b')
>>> print(t)
['a', 'c']

#Constructing a List with List Items:

LetsUpgrade_Community = [['Frontend', 'Backend'],['Sai Sir', 'Viral Sir', 'Prasad Sawant', 'Annirudha', 'Yogesh Raghupati']]

The lists within a list are called nested list.

To access an item within this list, we will have to use multiple indices:

print(LetsUpgrade_Community[1][0])
print(LetsUpgrade_Community[0][0])
	
Output
Sai Sir
Frontend

#List and Strings:

Assuming that by now you know the difference between String and List, let’s convert a STRING to a list of CHARACTERS as shown below –

>>> s = 'LetsUpgrade'
>>> t = list(s)
>>> print(t)
['L', 'e', 't', 's','U', 'p', 'g', 'r', 'a','d', 'e']

To break a string into words, we can use the split method –

>>> s = 'FREE CODING SCHOOL'
>>> t = s.split()
>>> print(t)
['FREE', 'CODING', 'SCHOOL']
>>> print(t[2])
SCHOOL

Delimiter: A delimiter is a sequence of one or more characters used to specify the boundary between separate, independent regions in plain text or other data streams.

>>> s = 'spam-spam-spam'
>>> delimiter = '-'
>>> s.split(delimiter)
['spam', 'spam', 'spam']

JOIN: It is the inverse of split.

>>> t = ['I am', 'a', 'LetsUpgrade', 'Student']
>>> delimiter = ' '
>>> delimiter.join(t)
'I am a LetsUpgrade Student'

#Parsing lines:

Usually when we are reading a file we want to do something to the lines other than just printing the whole line. Often we want to find the “interesting lines” and then parse the line to find some interesting part of the line. What if we wanted to print out the day of the week from those lines that start with “From”?

From [email protected] Sat Jan 5 09:14:16 2008

The split method is very effective when faced with this kind of problem. We can write a small program that looks for lines where the line starts with “From”, split those lines, and then print out the third word in the line:

fhand = open('mbox-short.txt')
for line in fhand:
    line = line.rstrip()
    if not line.startswith('From '): continue
    words = line.split()
    print(words[2])

The program produces the following output:

Sat
Fri
Fri
Fri

(Referrence: pythonlearn)

#Objects and values:

We will use ‘is‘ operator to check given two variables ‘a’ and ‘b’ refer to the same object or not:

>>> a = 'banana'
>>> b = 'banana'
>>> a is b
True
	
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
False

In the first example, Python only created one string object, and both a and b refer to it.

In the second case, we would say that the two lists are equivalent as they have the same elements, but not identical, because they are not the same object. If two objects are identical, they are also equivalent, but if they are equivalent, it is not necessary to be identical.

#Aliasing:

>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True

The association of a variable with an object is called a reference. In this example, there are two references to the same object.

An object with more than one reference has more than one name, then we say that particular object is aliased and If the aliased object is mutable, changes made with one alias affect the other:

>>> b[1] = 25
>>> print(a)
[1, 25, 3]

The above method seems to be useful but it is Error-prone and therefore, it is better to avoid using this method on mutable objects like list and for immutable objects like string is not much a problem.

#List Arguments:

def delete(t):
    del t[0]
     
S = ['a', 'b', 'c']
delete (S)
print (S)
['b', 'c']

In the above example, when we pass a list to a function, the function gets a reference to the list. The caller sees the change if there is any modification in the list parameter done by function as in the above delete removes the first element from the list.

>>> t1 = [1, 2]
>>> t2 = t1.append(3)
>>> print(t1)
[1, 2, 3]
>>> print(t2)
None
	
>>> t3 = t1 + [3]
>>> print(t3)
[1, 2, 3]
>>> t2 is t3
False

In the above two examples, the first one is used to Modify the existing List and the second one is used to Create a new list. Thus, output of ‘ t2 is t3 ‘ is false unless we assign it as ‘ t2 = t3 ‘.

def tail(t):
    t = t[2:] 
    
letters = ['a', 'b', 'c', 'f','d']
rest = tail(letters)
print (rest)
None
	
def tail(t):
    t = t[2:]
    return t
         
letters = ['a', 'b', 'c', 'f','d']
rest = tail(letters)
print (rest)
['c', 'f', 'd']

If we compare above two examples, the output of both the examples vary and the reason is simple, the slice operator creates a new list and the assignment makes t refer to it, but none of that has any effect on the list that was passed as an argument.

Therefore, in second case it creates and returns a new list that is generated.

Exercise : Write a function called chop that takes a list and
modifies it, removing the first and last elements, and returns None. Then write a function called middle that takes a list and returns a newlist that contains all but the first and last elements.

#List Comprehensions:

It is a complex topic and to understand it properly you need go through this below Article:

List Comprehension in Python

————————————- THE END———————————————

Previously published at https://olinelearning13.wordpress.com/2020/05/29/python-3-list-in-detail/