How to iterate over each element in a list? - python-3.x

I have a list of strings and I am iterating over each element by using a for loop, but it seems that what I am doing is iterating over each character instead of each element of the list. For instance:
names = list(input('Enter list of names:')).upper()))
result = []
for i in names:
if 'A' not in i and 'C' in i:
result.append('membership')
elif 'A' in i and 'C' not in i:
result.append('no_membership')
else:
result.append('unknow'):
print(result)
But what I am getting is a list in which the for loop is evaluating each character in the list of strings instead of each name. Am I doing something wrong in the code or do I need to split the elements of the list?

Logically you are just trying to add the entire input into one item of the list
So the first line should read something like:
names = input('Enter list of names:').upper().split()
This will split the inputted string by spaces into a list of separate strings.

Related

Get index of a list with tuples in which the first element of the tuple matches pattern

I have a list of tuples:
countries = [('Netherlands','31'),
('US','1'),
('Brazil','55'),
('Russia','7')]
Now, I want to find the index of the list, based on the first item in the tuple.
I have tried countries.index('Brazil'), I would like the output to be 2. But instead, that returns a ValueError:
ValueError: 'Brazil' is not in list
I am aware that I could convert this list into a pd DataFrame and then search for a pattern match within the first column. However, I suspect there is a faster way to do this.
You can use enumerate() to find your index:
Try:
idx = next(i for i, (v, *_) in enumerate(countries) if v == "Brazil")
print(idx)
Prints:
2

How a Python code to store integer in list and then find the sum of integer stored in the List

List of integer value passed through input function and then stored in a list. After which performing the operation to find the sum of all the numbers in the list
lst = list( input("Enter the list of items :") )
sum_element = 0
for i in lst:
sum_element = sum_element+int(i)
print(sum_element)
Say you want to create a list with 8 elements. By writing list(8) you do not create a list with 8 elements, instead you create the list that has the number 8 as it's only element. So you just get [8].
list() is not a Constructor (like what you might expect from other languages) but rather a 'Converter'. And list('382') will convert this string to the following list: ['3','8','2'].
So to get the input list you might want to do something like this:
my_list = []
for i in range(int(input('Length: '))):
my_list.append(int(input(f'Element {i}: ')))
and then continue with your code for summation.
A more pythonic way would be
my_list = [int(input(f'Element {i}: '))
for i in range(int(input('Length: ')))]
For adding all the elements up you could use the inbuilt sum() function:
my_list_sum = sum(my_list)
lst=map(int,input("Enter the elements with space between them: ").split())
print(sum(lst))

How to slice a list of strings till index of matched string depending on if-else condition

I have a list of strings =
['after','second','shot','take','note','of','the','temp']
I want to strip all strings after the appearance of 'note'.
It should return
['after','second','shot','take']
There are also lists which does not have the flag word 'note'.
So in case of a list of strings =
['after','second','shot','take','of','the','temp']
it should return the list as it is.
How to do that in a fast way? I have to repeat the same thing with many lists with unequal length.
tokens = [tokens[:tokens.index(v)] if v == 'note' else v for v in tokens]
There is no need of an iteration when you can slice list:
strings[:strings.index('note')+1]
where s is your input list of strings. The end slice is exclusive, hence a +1 makes sure 'note' is part.
In case of missing data ('note'):
try:
final_lst = strings[:strings.index('note')+1]
except ValueError:
final_lst = strings
if you want to make sure the flagged word is present:
if 'note' in lst:
lst = lst[:lst.index('note')+1]
Pretty much the same as #Austin's answer above.

Recreate the code without list comprehension

I am learning about list comprehension therefore i would like to recreate the code without list comprehension.
The code is the following:
items=[x for x in input().split(",")]
items.sort()
print (items)
This is how i recreated it:
print ("Enter comma seperated words: ")
userinput = input ().split(",")
words = []
for i in range (len(userinput)):
words.append(userinput)
words.sort()
print (words)
I expect the output should be in alphabetical order but it does not.
Let's say our input is this...
userinput = 'foo,bar'
Using the list comprehension code...
items=[x for x in userinput.split(",")]
items.sort()
print (items)
Output becomes: `['bar', 'foo']`
However, if we use your recreated code..
userinput = userinput.split(',')
words = []
for i in range (len(userinput)):
words.append(userinput)
words.sort()
print (words)
Output becomes: `[['foo', 'bar']]
Why is this?
When the line userinput = userinput.split(',') is run, userinput now becomes ['foo', 'bar'].
Therefore, when words.append(userinput) is run, what it is actually doing is saying words.append(['foo', 'bar']), and thus you are appending a list into a list meaning that words = [['foo', 'bar']].
words.sort() will not sort nested lists within itself, therefore, your list isnt sorted.
Therefore the fix is to append each element of userinput into words instead of appending userinput as a list into words.
userinput = userinput.split(',')
words = []
for i in range (len(userinput)):
words.append(userinput[i])
words.sort()
print (words)
Output becomes: ['bar', 'foo']

How to delete substring from a list and have a full string of it present in list?

I have a python list having many sub-strings of a full string including the full string. Can someone help me to remove all the sub-strings from the list and have only full string.
lists = ['ab','bcd','cd','abcd','ef']
For the above input, i want the output to be as:
lists = ['abcd','ef']
Please note, not to consider the string length from this example since my actual list items length is much fluctuating.
This is not python code, but my algorithm. Hope it works
Let have 2 arrays, array1 for input and array2 for result
Find longest length element in array
For each element in array1, check with shorter elements:
if included [duplicate] -> Remove
if not keep
Add this long element in new array2 and
remove from array1
For those kept elements
Do step 2 again until finish
if only 1 element left in array1
. just add it to array2
import copy
listA = ['abc','bcd','abcd', 'ef', 'eef']
listB=copy.deepcopy(listA) # create 2nd copy of main list
new_list=[]
global longest_str
longest_str=max(listA, key=len)
l_len=len(listA)
while l_len>0:
for l in listB:
if l in longest_str and len(l)<len(longest_str):
listA.remove(l) # remove the sub-string
if longest_str == l:
new_list.append(l) #append longest string in new_list
listA.remove(l) #remove from the main list
l_len=len(listA)
if l_len>0:
longest_str=max(listA, key=len)
print(new_list)

Resources