473,657 Members | 2,753 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How can I create a linked list in Python?

with a cell class like this:

#!/usr/bin/python

import sys

class Cell:

def __init__( self, data, next=None ):
self.data = data
self.next = next

def __str__( self ):
return str( self.data )

def echo( self ):
print self.__str__()
Jan 16 '07 #1
19 7815
Dongsheng Ruan wrote:
with a cell class like this:

#!/usr/bin/python

import sys

class Cell:

def __init__( self, data, next=None ):
self.data = data
self.next = next

def __str__( self ):
return str( self.data )

def echo( self ):
print self.__str__()
If you really want a list (as Python defines a list - with all the methods) then you should use Python's lists. They are quite efficient and convenient:

l = [Cell(1), Cell(2), Cell(3)]

However, if what you want is each cell to refer to a next cell (which after all is what a linked list does), then you already have it with the next attribute. (In other languages you might implement 'next' as a pointer, while in Python we call it a reference -- but it amounts to the same thing.) Create it this way:

c = Cell(3)
b = Cell(2, c)
a = Cell(1, b)

or

a = Cell(1, Cell(2, Cell(3)))

However, I'll repeat this: The concept of a linked list if a figment of languages with pointer data types. Python abstracts that by allowing attributes to contain references to other objects. However, you're much better off if you can use Python's list data structure rather than try to emulate an outdated concept in a modern language.

Gary Herron

Jan 16 '07 #2
How can I implement a linked list like the implementations in c with
struct-s and arrays (or pointers).
to simbolize the working principe

Gary Herron je napisao/la:
Dongsheng Ruan wrote:
with a cell class like this:

#!/usr/bin/python

import sys

class Cell:

def __init__( self, data, next=None ):
self.data = data
self.next = next

def __str__( self ):
return str( self.data )

def echo( self ):
print self.__str__()
If you really want a list (as Python defines a list - with all the methods) then you should use Python's lists. They are quite efficient and convenient:

l = [Cell(1), Cell(2), Cell(3)]

However, if what you want is each cell to refer to a next cell (which after all is what a linked list does), then you already have it with the next attribute. (In other languages you might implement 'next' as a pointer, while in Python we call it a reference -- but it amounts to the same thing.) Create it this way:

c = Cell(3)
b = Cell(2, c)
a = Cell(1, b)

or

a = Cell(1, Cell(2, Cell(3)))

However, I'll repeat this: The concept of a linked list if a figment of languages with pointer data types. Python abstracts that by allowing attributes to contain references to other objects. However, you're much better off if you can use Python's list data structure rather than try to emulate an outdated concept in a modern language.

Gary Herron
Jan 16 '07 #3
Thanks for your kindly help.
I am new CS student taking datat structure and algorithms with AHO's book
with the same title.

The book is done in Pascal, which might be an outdated language.

However, my instructor probably wants us to understand the list ADT better
by not using the built in list in Python.

"Gary Herron" <gh*****@island training.comwro te in message
news:ma******** *************** *************** *@python.org...
Dongsheng Ruan wrote:
>with a cell class like this:

#!/usr/bin/python

import sys

class Cell:

def __init__( self, data, next=None ):
self.data = data
self.next = next

def __str__( self ):
return str( self.data )

def echo( self ):
print self.__str__()
If you really want a list (as Python defines a list - with all the
methods) then you should use Python's lists. They are quite efficient and
convenient:

l = [Cell(1), Cell(2), Cell(3)]

However, if what you want is each cell to refer to a next cell (which
after all is what a linked list does), then you already have it with the
next attribute. (In other languages you might implement 'next' as a
pointer, while in Python we call it a reference -- but it amounts to the
same thing.) Create it this way:

c = Cell(3)
b = Cell(2, c) a = Cell(1, b)

or

a = Cell(1, Cell(2, Cell(3)))

However, I'll repeat this: The concept of a linked list if a figment of
languages with pointer data types. Python abstracts that by allowing
attributes to contain references to other objects. However, you're much
better off if you can use Python's list data structure rather than try to
emulate an outdated concept in a modern language.

Gary Herron

Jan 16 '07 #4
Gary Herron:
If you really want a list (as Python defines a list - with all the methods) then you should use Python's lists. They are quite efficient and convenient:
In CPython they are dynamic arrays, they aren't lists. Try adding
elements at the beginning of a list compared to adding elements at the
beginning or in the middle of a python "list" and you will see the
efficiency differences.

The concept of a linked list if a figment of languages with pointer data types.
You may manage a list with a language without pointers, like *basic*
(for students) Scheme. Creating a List data type for Python is possible
too, without true pointer like ones found in Pascal.

>However, you're much better off if you can use Python's list data structure rather
than try to emulate an outdated concept in a modern language.
Simple lists today aren't much efficient because their pointers break
cache locality, they may cause cache trashing, so they may be slower
than smarter and more localized structures, like short double linked
arrays, etc.
But I think lists aren't outdated, they are a mathematical concept too,
and they are quite used still.
If you want to learn some Computer Science, it's positive to know what
linked lists are.
If you want to implement algorithms that must process LOT of things,
you may find pointers and lists quite necessary today too, see for
example:
http://citeseer.ist.psu.edu/knuth00dancing.html
http://en.wikipedia.org/wiki/Dancing_Links
Python and its data structures aren't the right solutions for all
purposes.

Bye,
bearophile

Jan 16 '07 #5

Dongsheng Ruan wrote:
with a cell class like this:

#!/usr/bin/python

import sys

class Cell:

def __init__( self, data, next=None ):
self.data = data
self.next = next

def __str__( self ):
return str( self.data )

def echo( self ):
print self.__str__()

Hi,

The "How to Think Like a Computer Scientist" free book has a chapter
just for this topic:

http://greenteapress.com/thinkpython/html/chap17.html

Regards,

Ray Smith
http://RaymondSmith.com

Jan 16 '07 #6
Dongsheng Ruan a écrit :
Thanks for your kindly help.
I am new CS student taking datat structure and algorithms with AHO's book
with the same title.

The book is done in Pascal, which might be an outdated language.
Yes, somehow - but note, that linked lists are the central data
structure of Lisp, which is probably the older programming language
still in use...

Implementing linked lists in Python is not a great deal - it just
doesn't make much sens. It's IMHO much more interesting to learn this
kind of stuff with a low-level language like C or Pascal.

However, my instructor probably wants us to understand the list ADT better
by not using the built in list in Python.
Indeed !-)

Jan 16 '07 #7
At Tuesday 16/1/2007 17:07, Dongsheng Ruan wrote:
>Thanks for your kindly help.
I am new CS student taking datat structure and algorithms with AHO's book
with the same title.

The book is done in Pascal, which might be an outdated language.

However, my instructor probably wants us to understand the list ADT better
by not using the built in list in Python.
Just use the same structure as the book. Instead of nil, use None;
instead of new(P) where P:^Foo, use P=Foo(); records become classes
without methods...

Anyway, implementing linked lists, dictionaries, and other basic
structures in a language like Pascal, or C -which doesn't have them
natively- may be a good learning exercise. But doing that in Python
is not a good idea. Of course, using Python in a second or third
algorithms course *is* a good idea, because you can forget about
these implementation details and concentrate on the algorithms.
--
Gabriel Genellina
Softlab SRL


_______________ _______________ _______________ _____
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas

Jan 17 '07 #8
Every language has its own way to do the business!
Python has a more abstract data type as the common tools.
Just do things in pythonic way!

On 1月17æ—¥, 上åˆ9æ—¶55分 , Gabriel Genellina
<gagsl...@yahoo .com.arwrote:
At Tuesday 16/1/2007 17:07, Dongsheng Ruan wrote:
Thanks for your kindly help.
I am new CS student taking datat structure and algorithms with AHO's book
with the same title.
The book is done in Pascal, which might be an outdated language.
However, my instructor probably wants us to understand the list ADT better
by not using the built in list in Python.Just use the same structure as the book. Instead of nil, use None;
instead of new(P) where P:^Foo, use P=Foo(); records become classes
without methods...

Anyway, implementing linked lists, dictionaries, and other basic
structures in a language like Pascal, or C -which doesn't have them
natively- may be a good learning exercise. But doing that in Python
is not a good idea. Of course, using Python in a second or third
algorithms course *is* a good idea, because you can forget about
these implementation details and concentrate on the algorithms.

--
Gabriel Genellina
Softlab SRL

_______________ _______________ _______________ _____
Preguntá. Respondé. DescubrÃ*.
Todo lo que querÃ*as saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!http://www.yahoo.com.ar/respuestas
Jan 17 '07 #9

Bruno Desthuilliers wrote:
Implementing linked lists in Python is not a great deal - it just
doesn't make much sens.
It does make sence, as there are memory constraints related to it.
Python lists are arrays under the hood. This is deliberately. Dynamic
arrays grows faster than lists for the common "short list" case, and
because indexing an array is O(1) instead of O(N) as it is for linked
lists. You can easily break the performance of Python lists by adding
objects in the middle of a list or appending objects to the end of long
lists. At some point the list can not grow larger by a simple realloc,
as it would crash with other objects on the heap, and the whole list
must be replaced by a brand new memory segment.

Also linked lists are an interesting theoretical concept in computer
science. Understanding how dynamic datastructures work and their
limitations are a key to understanding algorithms and how computers
work in general.

The simplest way of implementing a linked list in Python is nesting
Python lists. One may e.g. type something like:

#create
mylist = []

# push
mylist = [someobject, mylist]

# pop
mylist = mylist[1]

#iterate
cur = mylist
while cur:
cur = cur[1]

This is actually single linked list that behaves like a stack, i.e. the
last added element sits on top and one needs to iterate the list to get
to the first.

Those who know Lisp should be familiar with the concept of creating
dynamic data structures form nesting lists; it may be more unfamiliar
to C and Pascal programmers, as these languages do not support such
constructs. In Python one may also use a more explicit solution
involving classes for expressing linked lists, which would be more
familiar to C and Pascal programmers. In any case, making linked lists
are trivial in Python.

Jan 17 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
4592
by: Steve Lambert | last post by:
Hi, I've knocked up a number of small routines to create and manipulate a linked list of any structure. If anyone could take a look at this code and give me their opinion and details of any potential pitfalls I'd be extremely grateful. Cheers Steve
4
3597
by: JS | last post by:
I have a file called test.c. There I create a pointer to a pcb struct: struct pcb {   void *(*start_routine) (void *);   void *arg;   jmp_buf state;   int    stack; };   struct pcb *pcb_pointer;
0
1040
by: Shahriar Shamil Uulu | last post by:
Hi All, i have this program, ================================================================= class Node: def __init__(self,name=None,next=None): self.name=name self.next=next def __str__(self): return str(self.name)
7
19164
by: Indraseena | last post by:
Hi can anybody send me how to create a linked list program in C++. Basically I want to know how a node is handled in c++. I know this in c only. in c we create a structure and use that structure for ctreating nodes. how is this achieved in c++ . my c structure is: struct node
6
8642
by: Suyash Upadhyay | last post by:
Hi All, As a beginner in Computer Programming, I decided to create Linked List using recursion, but I am not getting right answer. I think it is fundamentally correct, but I am stuck. Please help me, #include "stdio.h" struct node { int n;
10
681
by: zfareed | last post by:
I have a program that creates a linked list and is required to count the number of elements in the list. This is what I have thus far. #include <iostream> using namespace std; struct listrec { int value; struct listrec *next; };
1
6177
by: yaarnick | last post by:
Create a linked list data structure library to hold strings. Then library should support the following linked list operations. Create() – Creates the linked list Insert() – Insert a string into the linked list Delete() – Deletes a string from the linked list Search() – Search for a string and return 1 if found otherwise return 0. isEmpty() – Returns 1 if the list is empty and 0 otherwise. Display() – Display all the strings in the list. ...
11
2542
by: Scott Stark | last post by:
Hello, The code below represents a singly-linked list that accepts any type of object. You can see I'm represting the Data variable a System.Object. How would I update this code to use generics instead of System.Object. I want the code in Form1_Load to remain exactly the same, but in the background I want to use generics. I'm trying to get a better understanding of how it works and I'm a little stuck.
19
3530
by: sedaw | last post by:
i need to create a linked lists in size =N each struct pointing to the next sruct the user will enter and the first struct pointed by constant pointer head. TNX ............. #include <stdio.h> #define size=5 void main() {
0
8382
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8297
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8816
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8717
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8600
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7311
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6162
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4150
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4300
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.