I got an issue to solve a problem.
When I run the code:
def get_state_name(list):
for lists in list:
print(lists)
mylist = ['a', 'b', 'c', 'd']
get_state_name(list)
It returns only 'a'
But without defining fuction, for example:
mylist = ['a', 'b', 'c', 'd']
for lists in mylist:
print(lists)
it returns entire list:
a
b
c
d
why is it happening?
Do not use the keyword "list"! It is default keyword and you should not use it for any other use (for ex variable name)
Also you are passing "list" as an argument in the last line, that variable is not defined outside of the function. You should pass "mylist" as your argument there.
Saying that, this is the code which will do the work. Compare it with yours.
Hope it will help:)
def get_state_name(my_list):
for lists in my_list:
print(lists)
mylist = ['a', 'b', 'c', 'd']
get_state_name(mylist)
You've Created mylist and passing wrong argument "list" .Just Because of this mistake
Correct Your Code :
def get_state_name(list):
for lists in list:
print(lists)
mylist = ['a', 'b', 'c', 'd']
get_state_name(mylist)
Now It Returns Correct Output
a
b
c
d
Related
I want to insert a word alphabetically into a list. Originally I would append the word I'm adding to the end of the list and then sort the list, but I am not allowed to use the sort() function.
Is there a way to do this through a function?
Based of of #SheshankS.'s answer. A function to do this for you:
def insert(item, _list):
for index, element in enumerate(_list):
if item < element: # in python, this automatically compares alphabetical precedence.
_list.insert(index, item)
return # exit out of the function since we already inserted
# if the item was not inserted, it must have the lowest precedence, so just append it
_list.append(item)
Note that since lists are mutable, this will actually mutate the given instance.
So, this:
someList = ["a", "b", "d"]
insert("c", someList)
Will actually change someList instead of just returning the new value.
Try doing this:
array = ["asdf", "bsdf", "kkkk", "zssdd"]
insertion_string = "zzat"
i = 0
for element in array:
if insertion_string < element:
array.insert(i, insertion_string)
break
i += 1
# if it is last one
if not insertion_string in array:
array.append(insertion_string)
print (array )
Repl.it = https://repl.it/repls/VitalAvariciousCodec
You did not say if you are allowed to use third-party modules, and you did not say if speed is a factor. If you want to add a new item to your sorted list quickly and you are allowed to use a module, use the SortedList class from sortedcontainers. This is a module included in many distributions of Python, such as Anaconda.
This will be simple and fast, even for large lists.
someList = SortedList(["a", "b", "d"])
someList.add("c")
print(someList)
The printout from that is
SortedList(['a', 'b', 'c', 'd'])
>>> import bisect
>>> someList = ["a", "b", "d"]
>>> bisect.insort(someList,'c')
>>> someList
['a', 'b', 'c', 'd']
>>>
If standard lib is allowed you can use bisect:
>>> import bisect
>>> lst = list('abcefg')
>>> for x in 'Adh':
... lst.insert(bisect.bisect(lst, x), x)
... print(lst)
...
['A', 'a', 'b', 'c', 'e', 'f', 'g']
['A', 'a', 'b', 'c', 'd', 'e', 'f', 'g']
['A', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
I want to make a loop for items in list that are not present in other_list, in one line. Something like this:
>>> list = ['a', 'b', 'c', 'd']
>>> other_list = ['a', 'd']
>>> for item in list not in other_list:
... print item
...
b
c
How is this possible?
for item in (i for i in my_list if i not in other_list):
print item
Its a bit more verbose, but its just as efficient, as it only renders each next element on the following loop.
Using set (which might do more than what you actually want to do) :
for item in set(list)-set(other_list):
print item
A third option: for i in filter(lambda x: x not in b, a): print(i)
list comprehension is your friend
>>> list = ['a', 'b', 'c', 'd']
>>> other_list = ['a', 'd']
>>> [x for x in list if x not in other_list]
['b', 'c']
also dont name things "list"
I am newbie to Python and I have a doubt regarding insert operation on the list.
Example 1:
mylist = ['a','b','c','d','e']
mylist.insert(len(mylist),'f')
print(mylist)
Output:
['a', 'b', 'c', 'd', 'e', 'f']
Example 2:
mylist = ['a','b','c','d','e']
mylist.insert(10,'f')
print(mylist)
Output:
['a', 'b', 'c', 'd', 'e', 'f']
In second example why it still inserts 'f' element in the list even if I am giving index 10 to insert method?
The list.insert function will insert before the specified index. Since the list is not that long anyways in your example, it goes on the end. Why not just use list.append if you want to put stuff on the end anyways.
x = ['a']
x.append('b')
print x
Output is
['a', 'b']
The concept here is "insert before the element with this index". To be able to insert at the end, you have to allow the invalid off-the-end index. Since there are no well-defined "off-the-end iterators" or anything in Python, it makes more sense to just allow all indices than to allow one invalid one, but no others.
I have a nested list that looks like this:
mylist = [['A;B', 'C'], ['D;E', 'F']]
I'd like to have it in the following form:
[['A', 'B', 'C'], ['D', 'E', 'F']]
Figured I'd write a simple list comprehension to do the task:
>>> newlist = [item[0].split(';').append(item[1]) for item in mylist]
>>> newlist
[None, None]
After some experimenting, I found that the error was in trying to use append() on anonymous lists:
>>> type(['A', 'B'])
<class 'list'>
>>> type(['A', 'B'].append('C'))
<class 'NoneType'>
Which seems like a gotcha, considering that you can do things like this:
>>> 'abc'.upper()
'ABC'
Obviously in most cases you could get around this by binding ['A', 'B'] to a variable before calling append(), but how would I make this work inside of a list comprehension? Furthermore, can anyone explain this unintuitive behavior?
[a.split(';') + [b] for a, b in mylist]
The problem is that you are storing the return value of the append() method, which is None.
One solution is to use itertools.chain() and store it in a list like so:
import itertools
mylist = [['A;B', 'C'], ['D;E', 'F']]
newlist = [list(itertools.chain(item[0].split(';'),item[1])) for item in mylist]
print newlist
prints:
[['A', 'B', 'C'], ['D', 'E', 'F']]
As you found out, mutating methods aren't of much use inside a list comprehension because the transient objects disappear immediately.
What works instead is to build-up a list through concatenation:
>>> mylist = [['A;B', 'C'], ['D;E', 'F']]
>>> [first.split(';') + [second] for first, second in mylist]
[['A', 'B', 'C'], ['D', 'E', 'F']]
As Will mentioned, the result of append() will be None, and you actually want the resulting list. Here is one option:
>>> mylist = [['A;B', 'C'], ['D;E', 'F']]
>>> mylist = [item[0].split(';') + [item[1]] for item in mylist]
>>> mylist
[['A', 'B', 'C'], ['D', 'E', 'F']]
Given input:
list = [['a']['a', 'c']['d']]
Expected Ouput:
mylist = a,c,d
Tried various possible ways, but the error recieved is TypeError: list indices must be integers not tuple.
Tried:
1.
k= []
list = [['a']['a', 'c']['d']]
#k=str(list)
for item in list:
k+=item
print k
2.
print zip(*list)
etc.
Also to strip the opening and closing parenthesis.
What you want is flattening a list.
>>> import itertools
>>> l
[['a'], ['a', 'c'], ['d']]
>>> res = list(itertools.chain.from_iterable(l))
>>> res
['a', 'a', 'c', 'd']
>>> set(res) #for uniqify, but doesn't preserve order
{'a', 'c', 'd'}
Edit: And your problem is, when defining a list, you should seperate values with a comma. So, not:
list = [['a']['a', 'c']['d']]
Use commas:
list = [['a'], ['a', 'c'], ['d']]
And also, using list as a variable is a bad idea, it conflicts with builtin list type.
And, if you want to use a for loop:
l = [['a'], ['a', 'c'], ['d']]
k = []
for sublist in l:
for item in sublist:
if item not in k: #if you want list to be unique.
k.append(item)
But using itertools.chain is better idea and more pythonic I think.
While utdemir's answer does the job efficiently, I think you should read this - start from "11.6. Recursion".
The first examples deals with a similar problem, so you'll see how to deal with these kinds of problems using the basic tools.