Can we add different class to first row and last row of view? Can we add different classes to first row and last row of view only ?

I have created a view of products listing in which i need to add unique class only in  first row and last row of view. 

I need to implement it for creating different designs layout of each row. 
In drupal 7 i did it by using below code :

 end($rows);
$last = key($rows);
?&gt;
&lt;?php if (!empty($title)): ?&gt;
&lt;h3&gt;&lt;?php print $title; ?&gt;&lt;/h3&gt;
&lt;?php endif; ?&gt;
&lt;?php foreach ($rows as $id =&gt; $row): ?&gt;
&lt;?php if ($id == $last): ?&gt;
&lt;?php $classes_array[$id] .= ' last-element'; ?&gt;
&lt;?php endif; ?&gt;
&lt;div&lt;?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?&gt;&gt;
&lt;?php print $row; ?&gt;
 &lt;/div&gt;


   

How we can do the same in drupal 8?
You would probably be fine with just doing this with css ( see Beebee's comment on your post), but I will answer the question.

You can use loop.first and loop.last in twig. Here is an example I used to make it work in a menu.

&lt;ul class="menu"&gt;
    {% for item in items %}
        {%
            set classes = [
            'menu-item',
            item.is_expanded ? 'menu-item--expanded',
            item.is_collapsed ? 'menu-item--collapsed',
            item.in_active_trail ? 'menu-item--active-trail',
        ]
        %}
        {% if loop.first %}
            &lt;li {{ item.attributes.addClass('first-element') }}&gt;
               {{ link(item.title, item.url) }}
               {% if item.below %}
                  {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
               {% endif %}
            &lt;/li&gt;
        {% endif %}
        {% if loop.last %}
            &lt;li{{ item.attributes.addClass('last-element') }}&gt;
                {{ link(item.title, item.url) }}
                {% if item.below %}
                    {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
                {% endif %}
            &lt;/li&gt;
        {% else %}
            &lt;li{{ item.attributes.addClass(classes) }}&gt;
                {{ link(item.title, item.url) }}
                {% if item.below %}
                    {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
                {% endif %}
            &lt;/li&gt;
        {% endif %}

    {% endfor %}
&lt;/ul&gt;