Create array/list with indexes

Asked

Viewed 501 times

0

Good morning guys, I started learning Python a few days ago and, doing some tests with lists around here I got some questions.

1 - In PHP I can create an array by defining the indexes of its values:

<?php
$array = array( 1 => 'Jan', 2 => 'Fev', ..., 12 => 'Dez' );
?>

But I couldn’t find a way to do the same in Python, can I? In the researches I did I ended up finding information about the index() function, which is not quite what I look for.

2 - These days, looking at some code around here, I found the following line:

your_list = [1,2,3]
a = [i for i in your_list]
a = [x+i for i in your_list for x in a]

print( a )

I understood what happens, basically it returns a list with the possible sums between the values in your_list: [1+1, 1+2, 1+3, 2+1, 2+2, 2+3, 3+1, 3+2, 3+3]. What got me curious here was how to rewrite the third line to separate the two for.

Thanks in advance.

2 answers

1

1. To define the indexes would need a dictionary instead of a list:

dict1 = {1: "Jan", 2: "Fev", ..., 12: "Dez"}

2. What happens in the code is a list comprehension, separate would look like this:

your_list = [1,2,3]
a = [i for i in your_list]
b = []
for i in your_list:
    for x in a:
        b.append(x + i)
a = b

print( a )
  • Thanks for the help, I will search more about List Comprehension

1


  1. Python does not offer type array as primitive type. You can work with listas, for example, that have indexes starting in 0. Another option, is you use modules: there is the module array of python import array and libraries like the Numpy.
    To create "distinct" python indexes has the type dicionário, where "indexes" (Keys) are associated with values.

    dictionary = {'1':Jan, '2': Fev, ... , '12': Dez}
    
  2. The second question was not very clear, but note that in the second line a is a copy of your_list. The code in the third line is equivalent to the following:

    list = []
    for i in your_list:
       for x in a:
          list.append(x+i)
    
  • Thanks for clearing my doubts, I’ll take a look at Numpy.

  • 1

    Remembering which indexes (Keys) in Python, there can be various types of immutable data, such as strings, numbers (float, long or int, both Taz) and tuples.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.