http://diveintopython3.ep.io/native-datatypes.html
I've found that link but it seems to rely on the fact that I first have to hard create the list. How can I create a list in Python if it's empty at first. I'm coming from a C# background so this is kind of weird so far.
For example the .append() method is what I'm looking for, but it relies on the fact that the list first exists. Any suggestions?
You can create an empty list like this
L=list()
or
L=[]
As noted by others, you can create an empty list with the list literal operator [].
Its worth noting that you can initialise the list with values if you always need to start with a few values already in place:
a = 5
L = [42, -12, a]
Related
I quite often use set() to remove duplicates from lists. After doing so, I always directly change it back to a list.
a = [0,0,0,1,2,3,4,5]
b = list(set(a))
Why does set() return a set item, instead of simply a list?
type(set(a)) == set # is true
Is there a use for set items that I have failed to understand?
Yes, sets have many uses. They have lots of nice operations documented here which lists don't have. One very useful difference is that membership testing (x in a) can be much faster than for a list.
Okay, by doubles you mean duplicate? and set() will always return a set because it is a data structure in python like lists. when you are calling set you are creating an object of set().
rest of the information about sets you can find here
https://docs.python.org/2/library/sets.html
As already mentioned, I won't go into why set does not return a list but like you stated:
I quite often use set() to remove doubles from lists. After doing so, I always directly change it back to a list.
You could use OrderedDict if you really hate going back to changing it to a list:
source_list = [0,0,0,1,2,3,4,5]
from collections import OrderedDict
print(OrderedDict((x, True) for x in source_list).keys())
OUTPUT:
odict_keys([0, 1, 2, 3, 4, 5])
As said before, for certain operations if you use set instead of list, it is faster. Python wiki has query TimeComplexity in which speed of operations of various data types are given. Note that if you have few elements in your list or set, you will most probably do not notice difference, but with more elements it become more important.
Notice that for example if you want to make in-place removal, for list it is O(n) meaning that for 10 times longer list it will need 10 times more time, while for set and s.difference_update(t) where s is set, t is set with one element to be removed from s, time is O(1) i.e. independent from number of elements of s.
I have a list that should contain all my other lists. Currently I append every list separately but that just looks pretty ugly..
looplist = [] # initiate an empty list that contains all date from the other lists
[...]
looplist.append(internallist1)
[...]
looplist.append(internallist10)
the internallists are all getting initialized and filled in a for loop
You can simply use + to merge them.
You may check for more info.
If you want to have list of lists, check this topic.
listOne.extend(anotherList)
this could help you: https://docs.python.org/3/tutorial/datastructures.html
you can also do listOne+=anotherList and this is less expensive, as it doesn`t involve a function call like extend
To answer what you are asking, Just initialize looplist with your 10 lists.
looplist = [internallist1,
internallist2,
internallist3] #Note: internallist3,] is also valid, python allows trailing comma. Nifty!
However, your 10 lists really shouldn't be separately named lists in the first place if this is your real use case. Just use looplist[0] through looplist[9] instead from the get go.
The zip method could work for you as you stated your output should:
look something like [ [list1], [list2], ... , [list n] ]
in your case the code would be similar to
looplist = list(zip(internallist1,[...], internallist10))
I am learning lists and trying to create a list and add data to it.
mylist=[]
mylist[0]="hello"
This generates Error.
Why cant we add members to lists like this, like we do with arrays in javascript.
Since these are also dynamic and we can add as many members and of any data type to it.
In javascript this works:
var ar=[];
ar[0]=333;
Why this dosent work in Python and we only use append() to add to list.
mylist[0] = 'hello' is syntactic sugar for mylist.__setitem__(0, 'hello').
As per the docs for object.__setitem__(self, key, value):
The same exceptions should be raised for improper key values as for
the __getitem__() method.
The docs for __getitem__ states specifically what leads to IndexError:
if value outside the set of indexes for the sequence (after any
special interpretation of negative values), IndexError should be
raised.
As to the purpose behind this design decision, one can write several chapters to explain why list has been designed in this way. You should familiarise yourself with Python list indexing and slicing before making judgements on its utility.
Lists in Python are fundamentally different to arrays in languages like C. You do not create a list of a fixed size and assign elements to indexes in it. Instead you either create an empty list and append elements to it, or use a list-comprehension to generate a list from a type of expression.
In your case, you want to add to the end, so you must use the .append method:
mylist.append('hello')
#["hello"]
And an example of a list comprehension:
squares = [x**2 for x in range(10)]
#[1,4,9,16,25,36,49,64,81,100]
If I have a list of strings and want to eliminate leading and trailing whitespaces from it, how can I use .strip() effectively to accomplish this?
Here is my code (python 2.7):
for item in myList:
item = item.strip()
print item
for item in myList:
print item
The changes don't preserve from one iteration to the next. I tried using map as suggested here (https://stackoverflow.com/a/7984192) but it did not work for me. Please help.
Note, this question is useful:
An answer does not exist already
It covers a mistake someone new to programming / python might make
Its title covers search cases both general (how to update values in a list) and specific (how to do this with .strip()).
It addresses previous work, in particular the map solution, which would not work for me.
I'm guessing you tried:
map(str.strip, myList)
That creates a new list and returns it, leaving the original list unchanged. If you want to interact with the new list, you need to assign it to something. You could overwrite the old value if you want.
myList = map(str.strip, myList)
You could also use a list comprehension:
myList = [item.strip() for item in myList]
Which many consider a more "pythonic" style, compared to map.
I'm answering my own question here in the hopes that it saves someone from the couple hours of searching and experimentation it took me.
As it turns out the solution is fairly simple:
index = 0
for item in myList:
myList[index] = item.strip()
index += 1
for item in myList:
print "'"+item+"'"
Single quotes are concatenated at the beginning/end of each list item to aid detection of trailing/leading whitespace in the terminal. As you can see, the strings will now be properly stripped.
To update the values in the list we need to actually access the element in the list via its index and commit that change. I suspect the reason is because we are passing by value (passing a copy of the value into item) instead of passing by reference (directly accessing the underlying list[item]) when we declare the variable "item," whose scope is local to the for loop.
I have two arrays, where if an element exists in an array received from a client then it should delete the matching array in the other array. This works when the client array has just a single element but not when it has more than one.
This is the code:
projects = ['xmas','easter','mayday','newyear','vacation']
for i in self.get_arguments('del[]'):
try:
if i in projects:
print 'PROJECTS', projects
print 'DEL', self.get_arguments('del[]')
projects.remove(i)
except ValueError:
pass
self.get_arguments('del[]'), returns an array from the client side in the format:
[u'xmas , newyear, mayday']
So it reads as one element not 3 elements, as only one unicode present.
How can I get this to delete multiple elements?
EDIT: I've had to make the list into one with several individual elements.
How about filter?
projects = filter(lambda a: a not in self.get_arguments('del[]'), projects)
Could try something uber pythonic like a list comprehension:
new_list = [i for i in projects if i not in array_two]
You'd have to write-over your original projects, which isn't the most elegant, but this should work.
The reason this doesn't work is that remove just removes the first element that matches. You could fix that by just repeatedly calling remove until it doesn't exist anymore—e.g., by changing your if to a while, like this:
while i in projects:
print 'PROJECTS', projects
print 'DEL', self.get_arguments('del[]')
projects.remove(i)
But in general, using remove is a bad idea—especially when you already searched for the element. Now you're just repeating the search so you can remove it. Besides the obvious inefficiency, there are many cases where you're going to end up trying to delete the third instance of i (because that's the one you found) but actually deleting the first instead. It just makes your code harder to reason about. You can improve both the complexity and the efficiency by just iterating over the list once and removing as you go.
But even this is overly complicated—and still inefficient, because every time you delete from a list, you're moving all the other elements of the list. It's almost always simpler to just build a new list from the values you want to keep, using filter or a list comprehension:
arguments = set(self.get_arguments('del[]'))
projects = [project for project in projects if project not in arguments]
Making arguments into a set isn't essential here, but it's conceptually cleaner—you don't care about the order of the arguments, or need to retain any duplicates—and it's more efficient—sets can test membership instantly instead of by comparing to each element.