Hi everyone could you please tell me if the following is a string, list or an array:
items = "a","b","c","d","e","f","g"
I am confused because lists or arrays would normally start with some sort of bracket? However, mine contains multiple objects but I'm not using brackets.
Please help.
Thank you!
It's a tuple of strings.
One way you can find out is using type:
>>> items = "a","b","c","d","e","f","g"
>>> type(items)
<class 'tuple'>
>>> type(items[0])
<class 'str'>
It is a tuple
When the elements are separated by just comas it is defaulted to a tuple.
You can also asign them to various variables:
itemA, itemB = "a", "b"
Related
I have this dictionary (ignore the "Rank" key):
dict={
"asset": [("S3","A1"),"S2",("E4","E5"),("E1","S1"),"A6","A8"],
"Rank": lirank,
"number_of_attributes":
}
Ι want to count the objects of the "asset" key and add it to "number_of_attributes" as a list.
Τhe output that I want is :
"number_of_attributes":[2,1,2,2,1,1]
the values come from the first object of asset ("S3","A1") having 2 items, the second ("S2") having 1 item, etc.
I would ideally like to write it with a for loop but I am open to other ideas.
you can use a list comprehension:
my_dict["number_of_attributes"] = [1 if isinstance(x, str) else len(x) for x in my_dict["asset"]]
print(my_dict["number_of_attributes"])
output:
[2, 1, 2, 2, 1, 1]
First, consider naming your variables different than dict, list or tuple.
Second, a solution to this issue is already provided here:
https://codereview.stackexchange.com/questions/97217/deep-length-of-a-list
For your specific case:
myDict={"asset":[("S3","A1"),"S2",("E4","E5"),("E1","S1"),"A6","A8"], "Rank": lirank }
myDict["number_of_attributes"] = [len(itm) if isinstance(itm, tuple) else 1 for itm in myDict["asset"]]
print(myDict["number_of_attributes"])
Here is a link to an online python repl for your problem: https://repl.it/repls/SuperiorDisastrousMuse
There are answers above that provides you with a fix for your problem. However, the reason that you are in trouble with this is that you are mixing datatypes in the asset list. This is not typically a good idea, and your problem here is a good example of why.
Normally, if you had a list of items and you wanted the "length" or "number_of_attributes", as you need in this case, you would just want to be able to do something like:
number_of_attribues = [len(x) for x in dict['asset']]
But len(..) behaves differently for tuple and string, and for string it doesn't give you the value you want (1) but the count of letters in the string (2).
This happens because the asset list you have has items of different data types. This list:
asset = [("S3","A1"),"S2",("E4","E5"),("E1","S1"),"A6","A8"]
is a list of tuples and strings mixed. You can see this by looping through the list and printing the data type:
>>> for a in asset:
... print(type(a))
...
<class 'tuple'>
<class 'str'>
<class 'tuple'>
<class 'tuple'>
<class 'str'>
<class 'str'>
If you can change your asset list to use lists instead of tuples, then you'd have a much simpler solution. Like so:
If you can change your input list to contain items of the same type:
asset_as_list = [["S3","A1"],["S2"],["E4","E5"],["E1","S1"],["A6"],["A8"]]
You now have a list of lists. The tuples are now a list of two items (you call them attributes here) and the strings are now a list of one item.
This will give you two good things:
1) It will allow you to get your number_of_attributes in a much simpler way:
>>> number_of_attribues = [len(x) for x in asset_as_list]
>>> number_of_attribues
[2, 1, 2, 2, 1, 1]
2) You don't mix datatypes in your list, and it will be much easier to work with in other situations as well as making your code easier to understand and debug. Which will become more important as your codebase grows larger and larger.
The list example is
inList = [1.1, 2017, 3+4j, 'superbowl', (4, 5), [1,2,3,5,12],{"make":'BMW', "model":'X5'}]
Basically I need to write a program that iterates through a list and prints each list element together with its data type.
New to python and need help getting started. Thanks
You wrote that "I need to write a program that iterates through a list and prints each list element together with its data type." And you were having a hard time because "I have tried google. only could find related material but nothing this specific."
Your real problem is you haven't learned to use Google to search for answers to programming questions. The key is to break your problem down into sub-problems and search for how to solve each one:
iterate through a list
get data type
print element and data type
I googled for python iterate through a list. The first result was Exercise 32: Loops and Lists from Learn Python the Hard Way which includes this code:
the_count = [1, 2, 3, 4, 5]
# this first kind of for-loop goes through a list
for number in the_count:
print "This is count %d" % number
And this result
This is count 1
This is count 2
This is count 3
This is count 4
This is count 5
Now I googled for python determine data type. The first result was Stack Overflow question How to determine the variable type in Python. Here is the relevant snippet from one of the answers:
Use type
>>> type(one)
<type 'int'>
So now we know how to iterate and how to get a type. And we see how to print, but not how to print two things at once. Let's google for python print. The second result is Input and Ouput section of the Python 2.7 tutorial. It turns out there are many ways to print multiple things at once, but one simple example from the page is.
>>> print 'We are the {} who say "{}!"'.format('knights', 'Ni')
We are the knights who say "Ni!"
So put this all together and we get:
for item in inList:
print '{} {}'.format(item, type(item))
Which prints:
1.1 <type 'float'>
2017 <type 'int'>
(3+4j) <type 'complex'>
superbowl <type 'str'>
(4, 5) <type 'tuple'>
[1, 2, 3, 5, 12] <type 'list'>
{'make': 'BMW', 'model': 'X5'} <type 'dict'>
This is a very basic question that you could easily answer by just looking at the documentation about control flow.
for element in inList:
print element, type(element)
Short answer to your question is:
print map(lambda x: (x, type(x).__name__), inList)
Here used map function which takes two parameters:
Function to be applied;
Array to be iterated.
This function iterates over every element of your array and apply given function to each of them. Results of application placed in a new array which this function return.
Also, here you can see lambda keyword which defines anonymous function. It takes x as parameter and then return pair containing this parameter and stringification of its type.
This question already has answers here:
How to create a "singleton" tuple with only one element
(4 answers)
Closed 9 days ago.
So I am trying to do this:
tuple([1])
The output I expect is :
(1)
However, I got this:
(1,)
But if I do this:
tuple([1,2])
It works perfectly! like this:
(1,2)
This is so weird that I don't know why the tuple function cause this result.
Please help me to fix it.
This is such a common question that the Python Wiki has a page dedicated to it:
One Element Tuples
One-element tuples look like:
1,
The essential element here is the trailing comma. As for any
expression, parentheses are optional, so you may also write
one-element tuples like
(1,)
but it is the comma, not the parentheses, that define the tuple.
That is how tuples are formed in python. Using just (1) evaluates to 1, just as much as using (((((((1))))))) evaluates to ((((((1)))))) to (((((1))))) to... 1.
Using (1,) explicitly tells python you want a tuple of one element
What you are getting is a tuple. When there is only a single element, then it has to be represented with a comma, to show it is a tuple.
Eg)
>>> a = (1)
>>> type(a)
<type 'int'>
>>> a = (1,)
>>> type(a)
<type 'tuple'>
>>>
The reason is, when you do not use a comma when there is only one element, the interpreter evaluates it like an expression grouped by paranthesis, thus assigning a with a value of the type returned by the expression
If you wanted to convert it to your expected representation (i.e. (1)), which as mentioned by others isn't a tuple for the singular case, you can use this approach - which will generate a string formatted output as the singular case isn't a valid tuple:
f"({str(your_list)[1:-1]})"
E.g
>>> f"({str([1])[1:-1]})"
'(1)'
>>> f"({str([1,2])[1:-1]})"
'(1,2)'
use
.format(str(tuple(mwo)).replace(",)",")")))
This will replace comma from the first element.
From the docs
6.2.3. Parenthesized forms
A parenthesized form is an optional expression list enclosed in parentheses:
parenth_form ::= "(" [expression_list] ")" A parenthesized expression
list yields whatever that expression list yields: if the list contains
at least one comma, it yields a tuple; otherwise, it yields the single
expression that makes up the expression list.
An empty pair of parentheses yields an empty tuple object. Since
tuples are immutable, the rules for literals apply (i.e., two
occurrences of the empty tuple may or may not yield the same object).
Note that tuples are not formed by the parentheses, but rather by use
of the comma operator. The exception is the empty tuple, for which
parentheses are required — allowing unparenthesized “nothing” in
expressions would cause ambiguities and allow common typos to pass
uncaught.
So (1,) really is a tuple
(1) is just 1 in grouping parentheses - it's an integer. (1,) is the 1-element tuple you want.
That is normal behavior in Python. You get a Tuple with one element. The notation (1,) is just a reminder that you got such a tuple.
The output (1,) is fine. The , is to mark a single element tuple.
If
a = (1)
a is really a integer
If
a = (1, )
Then a is a tuple.
what is the difference between curly brace and square bracket in python?
A ={1,2}
B =[1,2]
when I print A and B on my terminal, they made no difference. Is it real?
And sometimes, I noticed some code use {} and [] to initialize different variables.
E.g. A=[], B={}
Is there any difference there?
Curly braces create dictionaries or sets. Square brackets create lists.
They are called literals; a set literal:
aset = {'foo', 'bar'}
or a dictionary literal:
adict = {'foo': 42, 'bar': 81}
empty_dict = {}
or a list literal:
alist = ['foo', 'bar', 'bar']
empty_list = []
To create an empty set, you can only use set().
Sets are collections of unique elements and you cannot order them. Lists are ordered sequences of elements, and values can be repeated. Dictionaries map keys to values, keys must be unique. Set and dictionary keys must meet other restrictions as well, so that Python can actually keep track of them efficiently and know they are and will remain unique.
There is also the tuple type, using a comma for 1 or more elements, with parenthesis being optional in many contexts:
atuple = ('foo', 'bar')
another_tuple = 'spam',
empty_tuple = ()
WARNING_not_a_tuple = ('eggs')
Note the comma in the another_tuple definition; it is that comma that makes it a tuple, not the parenthesis. WARNING_not_a_tuple is not a tuple, it has no comma. Without the parentheses all you have left is a string, instead.
See the data structures chapter of the Python tutorial for more details; lists are introduced in the introduction chapter.
Literals for containers such as these are also called displays and the syntax allows for procedural creation of the contents based of looping, called comprehensions.
They create different types.
>>> type({})
<type 'dict'>
>>> type([])
<type 'list'>
>>> type({1, 2})
<type 'set'>
>>> type({1: 2})
<type 'dict'>
>>> type([1, 2])
<type 'list'>
These two braces are used for different purposes. If you just want a list to contain some elements and organize them by index numbers (starting from 0), just use the [] and add elements as necessary. {} are special in that you can give custom id's to values like a = {"John": 14}. Now, instead of making a list with ages and remembering whose age is where, you can just access John's age by a["John"].
The [] is called a list and {} is called a dictionary (in Python). Dictionaries are basically a convenient form of list which allow you to access data in a much easier way.
However, there is a catch to dictionaries. Many times, the data that you put in the dictionary doesn't stay in the same order as before. Hence, when you go through each value one by one, it won't be in the order you expect. There is a special dictionary to get around this, but you have to add this line from collections import OrderedDict and replace {} with OrderedDict(). But, I don't think you will need to worry about that for now.
a = "Stack"
aList = list(a)
This gives me an array like this ['S','t',a','c','k']
I want to know how this list(string) function works!
A string is an iterable type. For example, if you do this:
for c in 'string':
print c
You get
s
t
r
i
n
g
So passing a string to list just iterates over the characters in the string, and places each one in the list.
String is iterable in python because you can do
>>> for ch in "abc":
... print ch
...
a
b
c
>>>
and if you take a look at list class construtor using help("list") in your python interpreter
class list(object)
| list() -> new empty list
| list(iterable) -> new list initialized from iterable's items
So, list("hello") returns a new list initialized.
>>> x = list("hello")
>>> type(x)
<type 'list'>
>>>
This works because str implements __iter__, which allows iter(obj) to be called on the object. For str, the implementation returns character by character.
Most of the work is actually being done by the string. You are actually using the constructor of the list type. In Python, we are usually not so concerned with what things are, but rather with what they can do.
What a string can do is it can give you (e.g. for the purpose of using a for loop) its characters (actually, length-1 substrings; there isn't a separate character type) one at a time. The list constructor expects any object that can do this, and constructs a list that contains the elements thus provided.