If I have a list in python, how can I create a reference to part of the list? For example:
myList = ["*", "*", "*", "*", "*", "*", "*", "*", "*"]
listPart = myList[0:7:3] #This makes a new list, which is not what I want
myList[0] = "1"
listPart[0]
"1"
Is this possible and if so how would I code it?
Cheers, Joe
List literals are written within square brackets [ ]. Lists work similarly to strings -- use the len() function and square brackets [ ] to access data, with the first element at index 0.
Python – Find Index or Position of Element in a List. To find index of the first occurrence of an element in a given Python List, you can use index() method of List class with the element passed as argument. The index() method returns an integer that represents the index of first match of specified element in the List.
We can use the in-built python List method, count(), to check if the passed element exists in the List. If the passed element exists in the List, the count() method will show the number of times it occurs in the entire list. If it is a non-zero positive number, it means an element exists in the List.
You can write a list view type. Here is something I have written as experiment, it is by no means guaranteed to be complete or bug-free
class listview (object):
def __init__(self, data, start, end):
self.data = data
self.start, self.end = start, end
def __repr__(self):
return "<%s %s>" % (type(self).__name__, list(self))
def __len__(self):
return self.end - self.start
def __getitem__(self, idx):
if isinstance(idx, slice):
return [self[i] for i in xrange(*idx.indices(len(self)))]
if idx >= len(self):
raise IndexError
idx %= len(self)
return self.data[self.start+idx]
def __setitem__(self, idx, val):
if isinstance(idx, slice):
start, stop, stride = idx.indices(len(self))
for i, v in zip(xrange(start, stop, stride), val):
self[i] = v
return
if idx >= len(self):
raise IndexError(idx)
idx %= len(self)
self.data[self.start+idx] = val
L = range(10)
s = listview(L, 2, 5)
print L
print s
print len(s)
s[:] = range(3)
print s[:]
print L
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
<listview [2, 3, 4]>
3
[0, 1, 2]
[0, 1, 0, 1, 2, 5, 6, 7, 8, 9]
You may assign to indices in the listview, and it will reflect on the underlying list. However,it does not make sense to define append or similar actions on the listview. It may also break if the underlying list changes in length.
Use a slice object or an islice iterator?
http://docs.python.org/library/functions.html#slice
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With