How to print middle element in list Python

This is a Python program to print the middle node(s) of a linked list.

The program creates a linked list using data items input from the user and prints the middle node(s) of the linked list.

1. Create a class Node with instance variables data and next. 2. Create a class LinkedList with instance variables head and last_node. 3. The variable head points to the first element in the linked list while last_node points to the last. 4. Define methods append and display inside the class LinkedList to append data and display the linked list respectively. 5. Define a function print_middle that prints the middle element(s) of the list. 6. The function print_middle iterates through the list to find its length and then iterates again to half its length. If the length of the list is even, it prints two middle elements.

7. Create an instance of LinkedList, append data to it and print its middle element(s).

Here is the source code of a Python program to print the middle element(s) of a linked list.

class Node: def __init__(self, data): self.data = data self.next = None     class LinkedList: def __init__(self): self.head = None self.last_node = None   def append(self, data): if self.last_node is None: self.head = Node(data) self.last_node = self.head else: self.last_node.next = Node(data) self.last_node = self.last_node.next     def print_middle(llist): current = llist.head length = 0 while current: current = current.next length = length + 1   current = llist.head for i in range((length - 1)//2): current = current.next   if current: if length % 2 == 0: print('The two middle elements are {} and {}.' .format(current.data, current.next.data)) else: print('The middle element is {}.'.format(current.data)) else: print('The list is empty.')     a_llist = LinkedList()   data_list = input('Please enter the elements in the linked list: ').split() for data in data_list: a_llist.append(int(data))   print_middle(a_llist)

1. An instances of LinkedList is created. 2. The user is prompted to enter the data items for the list.

3. The function print_middle is called to print the middle element(s) of the list.

Case 1: Please enter the elements in the linked list: 1 2 3 4 5 6 7 8 The two middle elements are 4 and 5.   Case 2: Please enter the elements in the linked list: 5 The middle element is 5.   Case 3: Please enter the elements in the linked list: 3 1 0 4 2 The middle element is 0.

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

Check this: Programming MCQs | Python Books

  • Get Free Certificate of Merit in Python Programming
  • Participate in Python Programming Certification Contest
  • Become a Top Ranker in Python Programming
  • Take Python Programming Tests
  • Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
  • Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

How to print middle element in list Python

Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.


middle value of a list in python

python by Yucky Yak on Dec 09 2020 Comment

Source: stackoverflow.com

middle value of a list in python

python by Yucky Yak on Dec 09 2020 Comment

Source: stackoverflow.com

Add a Grepper Answer


  • average value of list elements in python
  • how to revert a list python
  • how to rotate the list in python
  • how to prit a certian in a list python
  • square all elements in list python
  • middle of linked list
  • how to get something from a certian possition in a list python
  • python get average of list
  • median of a list python
  • add to middle of list python
  • python find the average of a list
  • python print list items vertically
  • python increase one item in list

  • how to get the middle element of a list python
  • how to find the middle number in a list in python
  • middle of a list python
  • find middle element in list python
  • python middle element of list
  • find middle of a list
  • python get the middle of a list
  • how to select middle index of a list in python
  • find the middle element of a list in python
  • how to find the middle element or elements in a list in python
  • how to find middle element of list in python
  • get middle value of list python
  • get the middle element of a list
  • how to print middle element in list python
  • how to get a middle item of a list py
  • middle of list
  • python how to find middle of list
  • list remove in the middle in python
  • how to find middle of list python
  • how to print the middle element in a list in python?
  • how to access middle element of list python
  • how to get middle value from a list in python
  • how to find the middle index in a list in python
  • how to find the middle poitn of a list
  • middle list python
  • how to find middle number in any list
  • how to find middle element in list in python
  • how to select a middle value from python list
  • middle value of python list
  • python find middle value in list
  • python get midpoint of list
  • how to isolate middle index of a list python
  • find middle number of list python
  • how to get middle element of a list in python
  • how to find middle of a list in pyhton
  • grab two middle elements from list
  • how to get middle number of a list in python
  • python find the middle of a list
  • how to find the middle elements in a list in python
  • print middle value from list python
  • how to find middle value in python list
  • python get middle of list
  • python middle of list
  • middle of list python
  • how to get the middle value of a list python
  • python how to get the middle number from a list
  • find middle element in a list python
  • how to find the middle number of a list in python
  • how to find the middle of a list in python
  • find left middle of a list python
  • know the middel element in list
  • how to find the middle item in a list python
  • how to find the middle of a list python
  • get the middle element of a list python
  • get middle number in list python
  • how to find the middle element in a list python
  • how to find middle value of a python list
  • get two middle value of list python
  • find the middle number in a list in python automatically
  • find item in middle of list python
  • how to find the middle elementof a list in python
  • get the middle element in a list python
  • middle element in list in python
  • grab middle vale list python
  • how do you find the middle element of a list in python?
  • middle element in a list python
  • how do you get the number that's in the middle of a list in python
  • hwo to find the middle value in a list
  • middle value of list python
  • find middle of a list python
  • element in the middle of a list python
  • find middle index of list python
  • find middle element of array in python
  • how to get the middle number from a list in python
  • how to print the middle value in a list python
  • how to find a middle number in python list
  • take a list and return the middle in python
  • middle element of list
  • take middle value element of list
  • how to get access to middle element of list in python
  • find middle item of list
  • print the values of a list from the middle\python
  • get middle element of list python
  • middle element of list python
  • how to find the middle element of a list in python
  • python find middle of list
  • python middle value of list
  • how to find the middle value of a list python
  • get middle index of list python
  • how to find the middle element in a list python
  • middle value of a list python
  • get middle of list python
  • find middle of list python
  • middle value of a list in python
  • how to get the middle of a list in python
  • how to move str to middle in list python
  • python code to get the middle item in a list
  • how to get middle element of a list
  • get the middle item in list python
  • how to find the middle value in a python list
  • print middle number of list
  • python middle of list definition
  • find middle number in list python
  • python find middle in list
  • python remove middle of list
  • python get middle element of list
  • find middle of list
  • python get the middle itemof a list
  • find middle value in list python
  • middle element in list python
  • return middle element of list
  • how to get the middle of the item in python
  • python select the middle of a list
  • find middle index python
  • get the middle value in list python
  • move a list a items to middle
  • how to find middle element in a list python
  • finding middle value in list python
  • how to print middle of list pythhon
  • take middle value of list
  • put and in middle of a list number
  • python chnage middle item of list
  • removing the middle value from a list python

by · Published February 6, 2021 · Updated October 25, 2021

If you want to find the middle element from a list then we can use following code.

My_List=[1,2,3,4,5,6,7] Middle_index=int((len(My_List)/2)) print(My_List[Middle_index]) #4

First, we will find the middle index of the list by dividing the length of the list by 2 then by the middle index, we can access a middle element of the list. But what if the length of the list is even. For example, if the length is odd then we can easily decide the middle number i.e. if there are 5 items then 2 items will be on the left side and 2 will be on the right side and 1 will be on the middle.

if the length of the list is even then we pick the first element of the second half i.e. if there are 4 items(even number ) then the first item of the second half will be item 3. Look at the following example.

My_List=[1,2,3,4,5,6] Middle_index=int((len(My_List)/2)) print(My_List[Middle_index]) #4

1,2,3 is the first half and 4,5,6 is the second half part so according to the above code 4(first element of the second half) will be the middle element of the list.

  1. Element-wise list operations in python:
  2. ways of changing the python list in place:
  3. Extended List slicing in python:
  4. check if a number is even or odd in python:
  5. Python List:
  6. Find maximum number from list:
  7. Find minimum number from a list:
  8. python program to find the area of a triangle:
  9. List pop() method:
  10. List sort() method:

Given a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3.
If there are even nodes, then there would be two middle nodes, we need to print the second middle element. For example, if given linked list is 1->2->3->4->5->6 then the output should be 4.

Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.

Method 1:
Traverse the whole linked list and count the no. of nodes. Now traverse the list again till count/2 and return the node at count/2.

Method 2:
Traverse linked list using two pointers. Move one pointer by one and the other pointers by two. When the fast pointer reaches the end slow pointer will reach the middle of the linked list.

Below image shows how printMiddle function works in the code :

How to print middle element in list Python



Python3

# Python3 program to find middle of

# the linked list

# Node class

class Node:

# Function to initialise the

# node object

def __init__(self, data):

# Assign data

self.data = data

# Initialize next as null

self.next = None

# Linked List class contains a

# Node object

class LinkedList:

# Function to initialize head

def __init__(self):

self.head = None

# Function to insert a new node at

# the beginning

def push(self, new_data):

new_node = Node(new_data)

new_node.next = self.head

self.head = new_node

# Print the linked list

def printList(self):

node = self.head

while node:

print(str(node.data) +

"->", end = "")

node = node.next

print("NULL")

# Function that returns middle.

def printMiddle(self):

# Initialize two pointers, one will go

# one step a time (slow), another two

# at a time (fast)

slow = self.head

fast = self.head

# Iterate till fast's next is null (fast

# reaches end)

while fast and fast.next:

slow = slow.next

fast = fast.next.next

# Return the slow's data, which would be

# the middle element.

print("The middle element is ", slow.data)

# Driver code

if __name__=='__main__':

# Start with the empty list

llist = LinkedList()

for i in range(5, 0, -1):

llist.push(i)

llist.printList()

llist.printMiddle()

# This code is contributed by Kumar Shivam (kshivi99)

Output:

5->NULL The middle element is [5] 4->5->NULL The middle element is [5] 3->4->5->NULL The middle element is [4] 2->3->4->5->NULL The middle element is [4] 1->2->3->4->5->NULL The middle element is [3]

Method 3:Initialize mid element as head and initialize a counter as 0. Traverse the list from head, while traversing increment the counter and change mid to mid->next whenever the counter is odd. So the mid will move only half of the total length of the list.

Thanks to Narendra Kangralkar for suggesting this method.

Python3

# Python program to implement

# the above approach

# Node class

class Node:

# Function to initialise the

# node object

def __init__(self, data):

# Assign data

self.data = data

# Initialize next as null

self.next = None

# Linked List class contains a

# Node object

class LinkedList:

# Function to initialize head

def __init__(self):

self.head = None

# Function to insert a new node at

# the beginning

def push(self, new_data):

new_node = Node(new_data)

new_node.next = self.head

self.head = new_node

# Print the linked list

def printList(self):

node = self.head

while node:

print(str(node.data) +

"->", end = "")

node = node.next

print("NULL")

# Function to get the middle of

# the linked list

def printMiddle(self):

count = 0

mid = self.head

heads = self.head

while(heads != None):

# Update mid, when 'count'

# is odd number

if count & 1:

mid = mid.next

count += 1

heads = heads.next

# If empty list is provided

if mid != None:

print("The middle element is ",

mid.data)

# Driver code

if __name__=='__main__':

# Start with the empty list

llist = LinkedList()

for i in range(5, 0, -1):

llist.push(i)

llist.printList()

llist.printMiddle()

# This code is contributed by Manisha_Ediga

Output:

5->NULL The middle element is [5] 4->5->NULL The middle element is [5] 3->4->5->NULL The middle element is [4] 2->3->4->5->NULL The middle element is [4] 1->2->3->4->5->NULL The middle element is [3]

Please refer complete article on Find the middle of a given linked list for more details!


Article Tags :

Linked List

Python

Python Programs

Adobe

Amazon

Flipkart

GE

Hike

Linked Lists

MAQ Software

Microsoft

Morgan Stanley

Nagarro

Payu

Qualcomm

Samsung

Veritas

VMWare

Wipro

Zoho

Practice Tags :

VMWare

Zoho

Flipkart

Morgan Stanley

Amazon

Microsoft

Samsung

Hike

Payu

MAQ Software

Adobe

Wipro

Qualcomm

Nagarro

GE

Veritas

Linked List