Python Forum
List-Elements as instances of a class
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
List-Elements as instances of a class
#1
Hi,

in my Python-Script have a class.
Based on that class, several instances should be generated.
But because I do not know how many instances I need when the code is executed, I want to use a list:


Example, how I thought it could work, but it doesn't:
class addresses():
   ...
   ...
   ...

for i, item in enumerate(address_liste):
   address[i] = addresses()



==> I cannot use lists for class-instances??? How to do it right?[/i]
Reply
#2
class Address(object):
    ...

addresses = []
for item in address_list:
    addresses.append(Address(item))
I'm assuming address_list is a list of data that goes into the Address class on initialization. You can shorten this to a list comprehension:
addresses = [Address(item) for item in address_list]
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
it works! Thank you! Thank you! Thank you! Thank you! Thank you!
Reply
#4
You can.  But the problem seems like you're not adding items to the list properly.  Use [].append() instead of indexing using an index that's out-of-bounds (which I think is how you add new elements in php).
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  unable to remove all elements from list based on a condition sg_python 3 377 Jan-27-2024, 04:03 PM
Last Post: deanhystad
Question mypy unable to analyse types of tuple elements in a list comprehension tomciodev 1 427 Oct-17-2023, 09:46 AM
Last Post: tomciodev
  How to read module/class from list of strings? popular_dog 1 424 Oct-04-2023, 03:08 PM
Last Post: deanhystad
Question [solved] Classes, assign an attributes to a class not to instances.. SpongeB0B 4 891 May-20-2023, 04:08 PM
Last Post: SpongeB0B
  Checking if a string contains all or any elements of a list k1llcod3 1 1,023 Jan-29-2023, 04:34 AM
Last Post: deanhystad
  How to change the datatype of list elements? mHosseinDS86 9 1,911 Aug-24-2022, 05:26 PM
Last Post: deanhystad
  ValueError: Length mismatch: Expected axis has 8 elements, new values have 1 elements ilknurg 1 5,013 May-17-2022, 11:38 AM
Last Post: Larz60+
  Class-Aggregation and creating a list/dictionary IoannisDem 1 1,883 Oct-03-2021, 05:16 PM
Last Post: Yoriz
  Why am I getting list elements < 0 ? Mark17 8 3,032 Aug-26-2021, 09:31 AM
Last Post: naughtyCat
  Looping through nested elements and updating the original list Alex_James 3 2,070 Aug-19-2021, 12:05 PM
Last Post: Alex_James

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020