Python - Count elements in list [duplicate] - python

This question already has answers here:
How do I get the number of elements in a list (length of a list) in Python?
(11 answers)
Closed 6 years ago.
I am trying to find a simple way of getting a count of the number of elements in a list:
MyList = ["a", "b", "c"]
I want to know there are 3 elements in this list.

len()
>>> someList=[]
>>> print len(someList)
0

just do len(MyList)
This also works for strings, tuples, dict objects.

len(myList) should do it.
len works with all the collections, and strings too.

len()
it will count the element in the list, tuple and string and dictionary,
eg.
>>> mylist = [1,2,3] #list
>>> len(mylist)
3
>>> word = 'hello' # string
>>> len(word)
5
>>> vals = {'a':1,'b':2} #dictionary
>>> len(vals)
2
>>> tup = (4,5,6) # tuple
>>> len(tup)
3
To learn Python you can use byte of python , it is best ebook for python beginners.

To find count of unique elements of list use the combination of len() and set().
>>> ls = [1, 2, 3, 4, 1, 1, 2]
>>> len(ls)
7
>>> len(set(ls))
4

You can get element count of list by following two ways:
>>> l = ['a','b','c']
>>> len(l)
3
>>> l.__len__()
3

Len won't yield the total number of objects in a nested list (including multidimensional lists). If you have numpy, use size(). Otherwise use list comprehensions within recursion.

Related

How can I print a list "nicely" and numbered? [duplicate]

This question already has answers here:
Accessing the index in 'for' loops
(26 answers)
Closed 12 months ago.
I need to print a list in Python nicely and numbered. For example, if this is my list:
list = ["hello", "dad", "milk"]
this is the output I want:
[1] -hello
[2] -dad
[3] -milk
This is what I have tried:
list = ["hello", "dad", "milk"]
list_element = 0
stuff = len(list)
while stuff != list_element:
element = list[list_element]
print(f"[{list_element}] -{element}")
list_element = list_element + 1
and this is the output I get:
[0] -hello
[1] -dad
[2] -milk
but I don't know how to make it start from 1 (I know in programming you start with 0, but I want to start with 1!)
edit:
I forgot to mention this was homework and we didn't learn about the for loop yet so my teacher said I shouldn't use it as to not confuse my classmates lol
You can simply to it using enumerate in Python, as follows:
list = ["hello", "dad", "milk"]
for i, element in enumerate(list, 1): # to start with index 1, instead of 0
print(f"[{i}] -{element}")
Result:
[1] -hello
[2] -dad
[3] -milk
You can get more informatoin and example about enumerate here:
https://www.programiz.com/python-programming/methods/built-in/enumerate
In additon, one tip is that it is not good to use pre-defined keyword as a variable name such as list.
You could also use enumerate.
myList = ["hello", "dad", "milk"]
for count, element in enumerate(myList):
print(f"[{count+1}] -{element}")

How do I check if a sublist in a 2D list is in a list? [duplicate]

This question already has answers here:
Check if list contains another list in python
(2 answers)
Closed 6 years ago.
I have two lists:
my_list = [1,2,3,4,5]
my_new_list = [[1,3,7,5],[1,2,3,4,5]]
How can I check that a sublist equals my_list?
If you want to check if my_list is in the my_new_list just use in:
>>> my_list in my_new_list
True
If you want to know the index of the matching list you can use index:
>>> my_new_list.index(my_list)
1
If you think these are too efficient, too easy or too short you can do it manually as well:
>>> any(sublist == my_list for sublist in my_new_list) # equivalent to "in"
True
>>> next(idx for idx, sublist in enumerate(my_new_list) if sublist == my_list) # like "index".
1
You can index built-in function
>>> my_new_list.index(my_list)
1
Or you can use in :
>>> my_list in my_new_list
True
You can also use magic function contains
>>> my_new_list.__contains__(my_list)
True

size of a whole list containing tuple [duplicate]

This question already has answers here:
How do I make a flat list out of a list of lists?
(34 answers)
Closed 6 years ago.
I have a list made of tuple
liste_groupe=((image1, image2, image6),(image5, image4, image8, image7, image3, image9))
and i would like to have the number of element of all the tuple ie here the result would be 9
I have tried len(liste_groupe) but it gives me 2.
So what code should I write in order to have the number of all the element of all the tuples in a list ?
There is no need to flatten the list in order to find the total length, and there is no need to use recursion if you already know the list is a simple 2D structure. This is all you need:
sum(map(len, liste_groupe))
Flatten a tuple of tuples into a list,
>>> liste_groupe=(('image1', 'image2', 'image6'),('image5', 'image4', 'image8', 'image7', 'image3', 'image9'))
>>> l = [item for t in liste_groupe for item in t]
>>> len(l)
9
# Or use itertools.chain
>>> import itertools
>>> l = list(itertools.chain(*liste_groupe))
>>> len(l)
9
If you only care about the number of elements,
>>> count = sum([len(t) for t in liste_groupe])
>>> count
9
You can follow a recursive approach:
def tuple_length( t ):
if type(t) != tuple:
return 1
length = 0
for element in t:
length += tuple_length( element )
return length
Now, tuple_length(liste_groupe) will return 9 as expected.
Recursion could accomplish this for you. With the following function the size of an n-dimensional tuple or list could be counted.
def calculate_size(data_set, size=0):
for i in data_set:
if isinstance(i, tuple) or isinstance(i, list):
size += calculate_size(i)
else:
size += 1
return size
Will work for a single nested list. For deeper or irregularly nested lists, you'll need a recursive function that uses chain.
from itertools import chain
cnt = len(list(chain.from_iterable(list_group)))

Delete list elements after using them [duplicate]

This question already has answers here:
Strange result when removing item from a list while iterating over it
(8 answers)
Closed 7 years ago.
I have a list
test_list = [1,2,3,4,5]
I want to iterate over the elements of this list and delete them after using. But when I try to do this
for element in test_list:
print element
test_list.remove(element)
Alternate elements are printed and removed from test_list
1
3
5
print test_list
[2, 4]
Please explain why this happens!
Read the answers to strange result when removing item from a list to understand why this is happening.
If you really need to modify your list while iterating do this:
>>> items = ['x', 'y', 'z']
>>> while items:
... item = items.pop()
... print item
...
z
y
x
>>> items
[]
Note that this will iterate in reverse order.
in python this concept is called an iterator
my_iter = iter(my_list)
each time you consume or look at an element it becomes gone ...

how to step through a list and accumulate a integer value telling how many times an element based on it's position in list was seen

I'm trying to see how many times an element has been seen in a list
for instance:
list = [125,130,140,123,125,140,130,140]
I want to figure out perhaps how many times the element in position 0 (here, 125) was seen in the list, and accumulate the value with a counter. For the element in position 0, I would want to yield the int, 2.
Actually, a complex machinery is unnecessary:
>>> l = [1, 2, 3, 2]
>>> l.count(l[1])
2
You can use Counter:
from collections import Counter
my_list = [125,130,140,123,125,140,130,140]
Counter(my_list)
Output:
Counter({140: 3, 130: 2, 125: 2, 123: 1})
Using list comprehension and len:
count = len([l for l in list if l == list[n]])
where n is the index of the item you are counting.
def foo(pos, values):
counter = 0
element_to_find = values[pos]
for element in values:
if element == element_to_find:
counter += 1
return counter
You could store them in a dictionary with a dict comprehension (which works exactly like list comprehensions):
l = [125,130,140,123,125,140,130,140]
counts = {x : l.count(x) for x in l}
Also, it is bad practice to name your list "list". This will conflict with the built-in list function in Python.

Categories

Resources