Lists in Python

Lists in Python

Hello Friends, How are you? Today I am going to solve the HackerRank Lists in Python Problem with a very easy explanation. In this article, you will get one or more than one approaches to solving this problem. So let’s start- {tocify} $title={Table of Contents}  Consider a list (list = []). You can perform the following commands:

  1. insert i e: Insert integer e at position i.
  2. print: Print the list.
  3. remove e: Delete the first occurrence of integer e.
  4. append e: Insert integer e at the end of the list.
  5. sort: Sort the list.
  6. pop: Pop the last element from the list.
  7. reverse: Reverse the list.
  8. Initialize your list and read in the value of n followed by n lines of commands where each command will be of the 7 types listed above. Iterate through each command in order and perform the corresponding operation on your list.
  • append 1: Append 1 to the list, arr = [1].
  • append 2: Append 2 to the list, arr = [1, 2].
  • insert 3 1: Insert 3 at index 1,arr = [1, 3, 2].
  • print: Print the array.

The first line contains an integer, n, denoting the number of commands. Each line i of the n subsequent lines contains one of the commands described above.

  • The elements added to the list must be integers.

For each command of type print, print the list on a new line.

12 insert 0 5 insert 1 10 insert 0 6 print remove 6 append 9 append 1 sort print pop reverse print {codeBox}

[6, 5, 10] [1, 5, 9, 10] [9, 5, 1] {codeBox}

1st Approach: Python Lists Solution

# ========================
# Information
# ======================== # Name: Lists in Python HackerRank Problem
# Direct Link:
# Difficulty: Easy
# Max Score: 10
# Language: Python 3 # ========================
# Solution Start
# ======================== # Lists in Python HackerRank Solution Start if __name__ == '__main__': N = int(input()) L=[]; for i in range(0,N): cmd=input().split() if cmd[0] == "insert": L.insert(int(cmd[1]),int(cmd[2])) elif cmd[0] == "append": L.append(int(cmd[1])) elif cmd[0] == "pop": L.pop() elif cmd[0] == "print": print(L) elif cmd[0] == "remove": L.remove(int(cmd[1])) elif cmd[0] == "sort": L.sort() else: L.reverse() # Lists in Python Hacker Rank Solution END
# MyEduWaves

Disclaimer: The above Problem ( Lists in Python ) is generated by Hackerrank but the Solution is Provided by MyEduWaves. This tutorial is only for Educational and Learning purposes. Authority if any queries regarding this post or website fill out the contact form. I hope you have understood the solution to this HackerRank Problem. All these three solutions will pass all the test cases. Now visit Python Lists Hackerrank Problem and try to solve it again.

No Comments

Sorry, the comment form is closed at this time.