Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
Solved

# access an attribute of a class from a list

Posted on 2009-05-03
Medium Priority
234 Views
I have the following class.
class chrom(object):
"""docstring for chrom"""
def __init__(self, chr, position, ma2c):
self.chr = chr
self.position = position
self.ma2c = ma2c
and then i have a list of this chrom objects called chromlist.

Let us imagine I want to create a sublist with the position of the items i to j from the chromlist!!!!

How would i do that in the esiest and most efficient way. I can' t do chromsublist[0:4].position???? why?
0
Question by:dfernan
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• 2

LVL 39

Assisted Solution

Roger Baklund earned 500 total points
ID: 24291456
chromsublist[0:4] does return the sublist (slice in python lingo), but you can not do chromsublist[0:4].position, because the list object does not have a 'position' property. This sublist contains 5 objects, each object have the 'position' property, so you need to use a loop to access it:
``````positions = []
for c in chromsublist[0:4]:
positions.append(c.position)
print positions
``````
0

LVL 39

Accepted Solution

Roger Baklund earned 500 total points
ID: 24291474
Sorry, the [0:4] slice contains 4 objects, not 5!

You could also make the list with a single statement:
``````# using map and lambda:
print map(lambda c:c.position,chromsublist[0:4])

# using list comprehension
print [x.position for x in chromsublist[0:4]]
``````
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Installing Python 2.7.3 version on Windows operating system For installing Python first we need to download Python's latest version from URL" www.python.org " You can also get information on Python scripting language from the above mentioned we…
Dictionaries contain key:value pairs. Which means a collection of tuples with an attribute name and an assigned value to it. The semicolon present in between each key and values and attribute with values are delimited with a comma.  In python we can…
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…
###### Suggested Courses
Course of the Month7 days, 3 hours left to enroll