This article is a part of a challenge series on Python. You can find the link to the previous articles in this series here:
- 30 Days of Python 👨💻 - Day One - Introduction
- 30 Days Of Python 👨💻 - Day 2 - Data Types I
- 30 Days of Python 👨💻 - Day 3 - Data Types II
As I am sharing my daily Python learning progress, it is becoming more clear and evident to me that learning and sharing explanations of concepts simultaneously helps solidify the building blocks even more. Another perk is the love from the community ❤️
Starting from where I left on day 3, I continued exploring about lists and the remaining data types today.
Actions on lists
Just like strings, Python provides us with some built-in methods to perform some actions on list data types. Again methods are called after the
. operator on objects (here lists). The actions can be classified based on their type of actions.
- scores = [44,48,55,89,34]
- scores.append(100) # Append adds a new item to the end
- print(scores) # [44, 48, 55, 89, 34, 100]
- scores.insert(0, 34) # Inserts 34 to index 0
- scores.insert(2, 44) # Inserts 44 to index 2
- print(scores) # [34, 44, 44, 48, 55, 89, 34, 100]
- scores.extend([23]) # Extend takes an iterable (loopable items) and adds to end of list
- print(scores) # [34, 44, 44, 48, 55, 89, 34, 100, 23]
- scores.extend([12,10])
- print(scores) # [34, 44, 44, 48, 55, 89, 34, 100, 23, 12, 10]
There is a little gotcha here. These methods add items to the list in-place and do not return any value.
- scores = [44,48,55,89,34]
- newScores = scores.append(100)
- print(newScores) # None
- newScores = scores.insert(0,44)
- print(newScores) # None
- languages = ['C', 'C#', 'C++']
- languages.pop()
- print(languages) # ['C', 'C#']
- languages.remove('C')
- print(languages) # ['C#']
- languages.clear()
- print(languages) # []
- alphabets = ['a', 'b', 'c']
- print(alphabets.index('a')) # 0 (Returns the index of the element in list
- print(alphabets.count('b')) # 1 (counts the ocurrence of an element
- numbers = [1,4,6,3,2,5]
- numbers.sort() # Sorts the list items in place and returns nothing
- print(numbers) # [1, 2, 3, 4, 5, 6] #Python also has a built in sorting function that returns a new list
- sorted_numbers = sorted(numbers) # note - this is not a method
- print(sorted_numbers) # [1, 2, 3, 4, 5, 6] numbers.reverse() # reverse the indices in place
- print(numbers) # [6, 5, 4, 3, 2, 1] numbers_clone = numbers.copy() # another approach is numbers[:]
- print(numbers_clone) # [6, 5, 4, 3, 2, 1]


Sandeep VemulaPosted Jul 16, 2020, 9:33 PM
Nice information. if possible include previous articles links in current article, it should be very helpfull.